Get Tag With Post ID In WordPress

Today i was writing my plugin and required each post tag to be placed into a variable outside of WordPress loop. I have a look at WordPress function reference api and did some Google and surprisingly i couldn't find it. After a long time of digging on Google, i finally found a clue. Apparently, the method get_the_tags takes in a post id! However, if you look at get_the_tags reference page, it doesn't mention at all. Hence, i decides to write it down here to ease people life in the future.

Get Tag In WordPress

Once you get hold of your Post ID you can easily retrieve the tag associated with the post with the following code.

			$postid = $post->ID;
			get_the_tags($postid);

It will return a list of tags. Hope it helps 🙂

Integrate Paypal Express Checkout Solution

As a web developer, there will surely be someday where you wish to integrate Paypal into one of your products or services. The most appropriate way is to read the documentation provided by Paypal. But reading it doesn't mean you will understand the documentation with one shot and this call for a lot of research and finding before your Paypal will work. I went through this process these few days that is why there wasn't much article written in the process.  Although it wasn't really difficult but going through the process of reading first before looking into their sample codes really wasn't the correct way of approaching this solution. Instead, looking into the sample code will definitely brings light to integrating Paypal express checkout solution (well, you still have to read a bit). In this article, i will try to demonstrate Paypal express checkout solution as simple as possible for you guys to be able to DIY.

Paypal Express Checkout

What is Paypal Express checkout solution? Paypal Express Checkout makes it easier for your customers to pay and allows you to accept PayPal while retaining control of the buyer and overall checkout flow. This means that you can integrate a payment solution with Paypal that retain most of the interaction on your website other than user login and verifying the product they are purchasing. Paypal express checkout also provides you with the ability to create recurring payment which can really eliminate the need to repurchase the exact service or product every single time. However, Paypal express checkout solution doesn't have the ability to allow your user to use credit card for purchases. Your customers must have Paypal in order to purchase with this solution. Credit card solution will only be available together with Paypal in Website Payment Pro solution. Hopefully this clear some doubt and help you select what solution you really need.

Integrate Paypal Express Checkout Solution - Step 1

Firstly, you might wonder where exactly are the correct documentation out of all the places in Paypal. You can get the documentation and Sample at the respective links. The sample is contain at the section PayPal API: Name-Value Pair Interface as i believe this will give you a better understanding on the flow of Paypal express check out solution. The sample files will required you to throw them  into your server and run (go to the browser and key in the url you have thrown the folder into) as it will simulate some of the payment flow you might want. Then you will look into the code and see how they are achieved. Please take note that localhost might not work for you as it will required you to have curl installed.

Integrate Paypal Express Checkout Solution - Step 2

Once the sample are placed into your server and you have play around, the next thing you might wonder is the exact file you will required to run your own Paypal express checkout solution. And here are the files you will only need.

  • APIError - display error
  • CallerService - main player that initial the talk
  • constants - all the required variables
  • SetExpressCheckout - display for step 1 of the process
  • GetExpressCheckoutDetails - display for step 2 of the process
  • DoExpressCheckoutPayment -  display for step 3 of the process + send final request to paypal
  • ReviewOrder - request handler for step 1 and responsible to redirect to step 2

The files i am looking at are all PHP files.  Well, the above file respective function should be self explained. The first 3 files(APIError, CallerService and Constants) are the files imported into the ReviewOrder and  DoExpressCheckoutPayment files as they are required to talk to Paypal. Once we understand this it is time to go into a more complicated stuff.

Integrate Paypal Express Checkout Solution - Step 3

To illustrate what is going on in the sample file, we will look at the following diagram provided by Paypal.

From left to right, we have 5 interfaces user will see. And two of them are display from Paypal where it is colored in blue (2nd and 3rd interface). Hence, we left with 3 interfaces which are SetExpressCheckout, GetExpressCheckoutDetails and DoExpressCheckoutPayment which is 1st, 4th and 5th interface respectively.  So we are all clear with the display files right now. Next we will need to know where ReviewOrder will appear. There are altogether 4 Calcuts as written on the diagram. The ReviewOrder will be triggered on the 2nd and 3rd Calcuts where SetExpressCheckout API and GETExpressCheckoutDetails API is being fired. Don't worry about what does these API means at the moment. Just treat them as a method that will tell Paypal what they do.

Integrate Paypal Express Checkout Solution - Step 4

I guess everyone should understand how Paypal work looking at the sample file and the explanation above.  Next i will explain some of the important things you will need to know since writing all the codes here is meaningless as they are the same for every sample files. It just makes it more confusing to read. Firstly, for each request made to Paypal, you will always see the following line in the sample file.

$resArray=hash_call("SetExpressCheckout",$nvpstr);

where $nvpstr is the name-value pair string passed into the method hash_call. What this function hash_call does it to send the request to Paypal to notify them the action you performing. In this case, SetExpressCheckout API is being performed here. There are also other API as mention previous such as GetExpressCheckoutDetails API and DoExpressCheckoutPayment API. These are the three API you will need to talk to Paypal in each stage shown on the previous diagram. So we should all clear about what does API mean that are written all over the Paypal documentation. The next important step is to know what name-value pair does each API required you to send in order for Paypal to understand you.

Integrate Paypal Express Checkout Solution - Step 5

Here we will see what does each API in the process of express checkout required. For SetExpressCheckout, you will required to have the following name-value pair in your string.

  • AMT
  • CURRENCYCODE
  • RETURNURL
  • CANCELURL
  • PAYMENTACTION

That is all! But in the sample it gives you more than just the above which is pretty good to understand what can be dump into the nvp string for it to display what you want on the paypal website where your user gets redirected.

For GetExpressCheckoutDetails API is pretty simple. It will just required you to have a token passed into the nvp string and this token can be retrieved via $_GET method where Paypal send it through there.

Lastly, for DoExpressCheckoutPayment API, you will need to provide the following nvp for it to work.

  • TOKEN
  • PAYERID
  • AMT
  • CURRENCYCODE
  • PAYMENTACTION

And that's it! The value forGetExpressCheckoutDetails and DoExpressCheckoutPayment API are provided by Paypal during the process while SetExpressCheckout data are given by you.

Summary

I believe the above explanations were pretty clear. But i still used quite a hell lots of time working on it *SLAP MYSELF*! This article is intended to provide any newbie on Paypal to get the hang of integrating Paypal without the need to spend time on reading and learning all about Paypal integration. However, the sample provided by Paypal is not secure and is only used to serve as a demonstration on 'how integration can be made easy'. I believe this article will be pretty useful for anyone to understand how Paypal work rather than reading few thousand words given by Paypal and never direct you to the correct sources or code (other than more documentation). Guess what? I found this Paypal Integration Wizard which is a wizard that creates all the above codes for you! :[

WordPress Text Formatting Problem – Solved!

In Hungred Dot Com, we have been having problem with text formatting in WordPress for all our codes due to WordPress smart quotes functionality. Most of us who write code for the public usually uses those smart plugin such as 'SyntaxHighlighter Evolved' to present it nicely to our users. The problem with using external plugins such as this is that WordPress smart quotes doesn't see the tag for the plugin in this case,


,
as one of excluding formatting tag. Tag such as 'pre', 'code', 'kbd', 'style', 'script', 'tt' are excluded from smart quotes which you can personally view it on the source code of WordPress located at wp-includes/formatting.php. Hence, your WordPress codes article will not be showing '"' instead of the normal '"' symbol. However, there are ways to solve such problem and here we will present them to you to eliminate all these trouble once and for all!

Include Tag In WordPress Text Formatting Function

One way to solve this problem is to add the plugin tag into the core function wptexturize which locate at wp-includes/formatting.php. In that file you will notice the following function,

/**
 * Replaces common plain text characters into formatted entities
 *
 * As an example,
 * <code>
 * 'cause today's effort makes it worth tomorrow's "holiday"...
 * </code>
 * Becomes:
 * <code>
 * ’cause today’s effort makes it worth tomorrow’s “holiday”…
 * </code>
 * Code within certain html blocks are skipped.
 *
 * @since 0.71
 * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
 *
 * @param string $text The text to be formatted
 * @return string The string replaced with html entities
 */
function wptexturize($text) {
	global $wp_cockneyreplace;
	$output = '';
	$curl = '';
	$textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
	$stop = count($textarr);
	
	/* translators: opening curly quote */
	$opening_quote = _x('“', 'opening curly quote');
	/* translators: closing curly quote */
	$closing_quote = _x('”', 'closing curly quote');
	
	$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt'));
	$no_texturize_shortcodes = apply_filters('no_texturize_shortcodes', array('code'));
	$no_texturize_tags_stack = array();
	$no_texturize_shortcodes_stack = array();

	// if a plugin has provided an autocorrect array, use it
	if ( isset($wp_cockneyreplace) ) {
		$cockney = array_keys($wp_cockneyreplace);
		$cockneyreplace = array_values($wp_cockneyreplace);
	} else {
		$cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
		$cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause");
	}

	$static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
	$static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, '’s', $closing_quote, ' ™'), $cockneyreplace);

	$dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
	$dynamic_replacements = array('’$1','$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');

	for ( $i = 0; $i < $stop; $i++ ) {
		$curl = $textarr[$i];

		if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0}
				&& empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) { // If it's not a tag
			// static strings
			$curl = str_replace($static_characters, $static_replacements, $curl);
			// regular expressions
			$curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
		} else {
			wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
			wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
		}

		$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
		$output .= $curl;
	}

	return $output;
}

You can add your tag into the function on this link,

$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt'));

for our example we will add [\php\]

$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt', ''));

Although this solved your problem but this solution also required you to edit the codes in the WordPress which will be replaced with every new release of WordPress.

Remove WordPress Text Formatting

The most efficient way is to remove the root of the problem! Unless you desperately want WordPress text formatting to be made available, you will want to remove this. Otto42 who is one of the moderator suggested a good way to eliminate such problem. We will add the following two code to remove the function wptexturize in WordPress which perform the formatting in our theme function.php file.

remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('the_content', 'wptexturize');
remove_filter('the_rss_content', 'wptexturize');

This way all your text and code will be safe from formatting on that theme. You can also create a very small plugin that do this by placing the above three links to ANY WordPress plugin (may be you don't even have to create any plugin for this).

Replace WordPress Default Text Formatting

For those who want WordPress smart quote to be enabled but doesn't want it to format your codes, you can try to replace the function wptexturize. You can do this on your theme or any plugin available for you. Basically, you can remove the default function wptexturize through the following code,

remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('the_content', 'wptexturize');
remove_filter('the_rss_content', 'wptexturize');

After that on the same page, you can copy the following code and add the action hook for your new wptexturize solution that cater to your personal need.

function my_wptexturize($text) {
	global $wp_cockneyreplace;
	$output = '';
	$curl = '';
	$textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
	$stop = count($textarr);
	
	/* translators: opening curly quote */
	$opening_quote = _x('“', 'opening curly quote');
	/* translators: closing curly quote */
	$closing_quote = _x('”', 'closing curly quote');
	
	$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt', ''));
	$no_texturize_shortcodes = apply_filters('no_texturize_shortcodes', array('code'));
	$no_texturize_tags_stack = array();
	$no_texturize_shortcodes_stack = array();

	// if a plugin has provided an autocorrect array, use it
	if ( isset($wp_cockneyreplace) ) {
		$cockney = array_keys($wp_cockneyreplace);
		$cockneyreplace = array_values($wp_cockneyreplace);
	} else {
		$cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
		$cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause");
	}

	$static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
	$static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, '’s', $closing_quote, ' ™'), $cockneyreplace);

	$dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
	$dynamic_replacements = array('’$1','$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');

	for ( $i = 0; $i < $stop; $i++ ) {
		$curl = $textarr[$i];

		if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0}
				&& empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) { // If it's not a tag
			// static strings
			$curl = str_replace($static_characters, $static_replacements, $curl);
			// regular expressions
			$curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
		} else {
			wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
			wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
		}

		$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
		$output .= $curl;
	}

	return $output;
}
remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('the_content', 'wptexturize');
remove_filter('the_rss_content', 'wptexturize');

add_filter('comment_text', 'my_wptexturize');
add_filter('the_excerpt', 'my_wptexturize');
add_filter('the_content', 'my_wptexturize');
add_filter('the_rss_content', 'my_wptexturize');

This way you will solved your problem of code being wrongly formatted and at the meantime have the capability of smart quote. The only fall back of this method is that you might need to maintain this code in the future if WordPress ever update this function so that you will always have the latest version of smart quote.

Article Formatted Solution

If your post have many articles and you haven't had this problem solved at the beginning, your visitors will still be seeing formatted code in your article and might just drive your visitors away! Hence, you might want to consider reversing the function of wptexturize to return the format for you. You can do this by adding the reversed version of wptexturize and placed in on either a plugin or your theme.

We used hungred smart quotes to solve our issue on the above mention matters.

Summary

Smart quote in WordPress can be annoying and troublesome. Nonetheless, it also benefits those who truly wanted such function built within WordPress as it might just destroy your layout due to the unencoded tag by other writers. Hence, for those who are troubled by this, hopefully the solutions above help!

WordPress Plugin Development Tips And Tricks

I have been developing WordPress plugin for a while now and it seems like there are always some correct and better ways of writing a particular code in WordPress than mindlessly trying to substitute it with pure PHP. However, these WordPress codes can only be found through countless reading and analyzing of codes from other WordPress sources. In this article, i will present as many tips and tricks i have seen in WordPress that can be very useful for wordpress plugin development.

Find Plugin Directory and URL With WordPress

Previously, i used to hard code the directory by using PHP function. However, after realize there is a better alternative in WordPress, i changed the way i find the plugin directory and URL.

In PHP,

$url = get_bloginfo('url')."/wp-content/plugins/plugin-name/images/hello.jpg";
$directory = dirname(__FILE__)."/plugin-name/images/hello.jpg";

Note: Using dirname(__FILE__) might not always end up on the plugin folder.

In WordPress,

$url = WP_PLUGIN_URL."/plugin-name/images/hello.jpg";
$directory = WP_PLUGIN_DIR."/plugin-name/images/hello.jpg";

Import CSS or JavaScript in WordPress

We love to code these import statement out to the function that performed the action. It can be on the admin page, write post page, home page, etc. But the correct way is to use WordPress action hook and built-in method.

Import CSS/JavaScript to Admin page

function hpt_loadcss()
{
	wp_enqueue_style('hpt_ini', WP_PLUGIN_URL.'/hungred-post-thumbnail/css/hpt_ini.css');
}
function hpt_loadjs()
{
	wp_enqueue_script('jquery');
	wp_enqueue_script('hpt_ini', WP_PLUGIN_URL.'/hungred-post-thumbnail/js/hpt_ini.js');
}
add_action('admin_print_scripts', 'hpt_loadjs');
add_action('admin_print_styles', 'hpt_loadcss');

Import to theme page

function ham_add_style()
{
	$style = WP_PLUGIN_URL . '/hungred-ads-manager/css/ham_template.css';
	$location = WP_PLUGIN_DIR . '/hungred-ads-manager/css/ham_template.css';
	if ( file_exists($location) ) {
		wp_register_style('template', $style);
		wp_enqueue_style( 'template');
	}
}
add_action('wp_print_styles', 'ham_add_style');

Both ways utilize the wp_enqueue_style/wp_enqeue_script method and action hook to import stylesheet and JavaScript properly into WordPress.

Separate Plugin Admin Code

This is only necessary if you are building a large plugin for WordPress. It is efficient to separate the admin codes from others by placing it on an external file so that the admin codes will not be complied by PHP when non-admin user or visitors are accessing your website.

if (is_admin())
include(‘admin.php’);

Secure your WordPress Query

Security something important for all of us. WordPress has a function escape() in their global variable $wpdb. It is best to use this for all data query in your WordPress to better secure your SQL query with the database to prevent any form of security attack. below shows an example,

 $welcome_name = "Mr. WordPress";
  $welcome_text = "Congratulations, you just completed the installation!";

  $insert = "INSERT INTO " . $table_name .
            " (time, name, text) " .
            "VALUES ('" . time() . "','" . $wpdb->escape($welcome_name) . "','" . $wpdb->escape($welcome_text) . "')";

  $results = $wpdb->query( $insert );

You may want to visit the presentation slide that have some interesting WordPress function used for securitySecure Coding with WordPress – WordCamp SF 2008 Slides

Use WordPress For Table Prefix

Never hard code your table prefix in WordPress! WordPress provides a variable in its global variable $wpdb that allows you to easily retrieve your table prefix.

global $wpdb;
$table_name = $wpdb->prefix . "liveshoutbox";

Get Absolute Path In WordPress

In WordPress, you can get the absolute path through the constant ABSPATH which is defined in WordPress.

require_once( ABSPATH . '/wp-includes/classes.php' );
require_once( ABSPATH . '/wp-includes/functions.php' );
require_once( ABSPATH . '/wp-includes/plugin.php' );

Determine Whether a Table Exist In WordPress

Wonder how to determine whether a table exist in your WordPress? You can use the following method to detect whether a particular table exist.

global $wpdb;
$table_name = $wpdb->prefix . "mytable";
if($wpdb->get_var("show tables like '$table_name'") == $table_name) {
	echo 'table exist!';
}

Always Record Table Version

This is an important tips. Always remember to record the version of your plugin table, so you can use that information later if you need to update the table structure. This can help in upgrading your table structure of the plugin in the future.

add_option("hungred_db_version", "1.0");

Create Table Using WordPress Method

This is important for many WordPress developers out there. Although we can create a table using the following method,

	$table = $wpdb->prefix."ham_form";
    $structure = "CREATE TABLE  `".$table."` (
		ham_id DOUBLE NOT NULL DEFAULT 1,
		ham_textarea longtext NOT NULL,
		ham_display longtext NOT NULL,
		UNIQUE KEY id (ham_id)
    );";
    $wpdb->query($structure);

Great! A table is created! Now, tell me how are you going to change this structure in the future? A better alternative is to use the function dbDelta in WordPress.

	$table = $wpdb->prefix."ham_form";
    $structure = "CREATE TABLE  `".$table."` (
		ham_id DOUBLE NOT NULL DEFAULT 1,
		ham_textarea longtext NOT NULL,
		ham_display longtext NOT NULL,
		UNIQUE KEY id (ham_id)
    );";
	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	dbDelta($structure);

Directly from WordPress,

The dbDelta function examines the current table structure, compares it to the desired table structure, and either adds or modifies the table as necessary, so it can be very handy for updates (see wp-admin/upgrade-schema.php for more examples of how to use dbDelta). Note that the dbDelta function is rather picky, however. For instance:

* You have to put each field on its own line in your SQL statement.
* You have to have two spaces between the words PRIMARY KEY and the definition of your primary key.
* You must use the key word KEY rather than its synonym INDEX

Hence, any update on the structure of the table will result in a change on the user plugin as well.

Use Nonces During Form Submission

Nonces are used as a security related protection to prevent attacks and mistakes. You can use Nonces to enhance your WordPress form. here is an example,

<form ...>
<?php
if ( function_exists('wp_nonce_field') )
	wp_nonce_field('hungred-post-form'+$uniqueobj);
?>
</form>

We are just using the method wp_nonce_field in WordPress to create a nonce field on the above example. Next, we will need to validate whether the nonce is valid by using the following method after the user have submitted the form. This should be placed before any action began.

<?php check_admin_referer('hungred-post-form'+$uniqueobj); ?>

Pretty easy for enhancing form in your WordPress plugin. But this is not all you can do. There is also Link nonce protection where link is attached with a Nonces. You can read more about Nonces from the below link.

They have better explanation and example to understand Nonce.

Speed up your WordPress plugin development with Ubiquity Firefox add-on

ubiquity

Ubiquity is a Mozilla Firefox add-on, developed by Mozilla Labs. It allows you to search WordPress and PHP (PHP) documentation in an instant. Safe time on Google, more time on development 😀

Tutorial: How to check whether a particular field exist on SQL table

I was doing some plugin enhancement when i needed to find out whether a field exist on the SQL table. Hence, i went Google and search for a good answer. I found two method to solve this problem but i prefer the one using pure SQL query. Hence, i decide to write them down for future use and also make it as a discussion regarding the pros and cons.

PHP Solution

The first solution i found was a method that used PHP and perform a calculation in order to conclude whether the field exist on the SQL table. Here's the snippets:

$fields = mysql_list_fields("databasename", "tablename");
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {
    $field_array[] = mysql_field_name($fields, $i);
}
       
if (!in_array(‘list_id’, $field_array)) {
    mysql_query("ALTER TABLE `tablename` ADD `fieldname` INT(11) NOT NULL DEFAULT ‘1′;");
}

From the above snippet provided by Antonie Potgieter, the concept is good but it is still not optimum. A better alternative can be written as follow.

$result = mysql_query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME ='tablename'");
$field_array = mysql_fetch_array($result);      
if (!in_array(‘list_id’, $field_array)) {
    mysql_query("ALTER TABLE `tablename` ADD `fieldname` INT(11) NOT NULL DEFAULT ‘1′;");
}

The code above have not been tested but the query, yes. Nonetheless, a loop can be removed anyhow by retrieving the set of array resist within the return value of mysql_fetch_array. The objective is to avoid loop and shorten the code as much as possible.

SQL Solution

I found a better alternative on DZone! I find that it is a much effective way to check the existence of a field. Here's the snippets:

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ‘TEST’ AND COLUMN_NAME = ‘TEST_DATE’)
BEGIN
   ALTER TABLE TEST ADD TEST_DATE DATETIME
END

Since we have taken away all the necessary code, only a direct query is needed in this case.

Summary

Which method would you prefer in this case? Why? Any better method than the one present above? I bet these two are the best we have for checking up a field existence unless you are talking about other languages than PHP. I would love to know your thoughts 🙂