<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Weblimner &#187; form</title>
	<atom:link href="http://www.weblimner.com/tag/form/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.weblimner.com</link>
	<description></description>
	<lastBuildDate>Sun, 15 Aug 2010 23:49:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Making of Q-List Plugin for Wordpres – 2 of 2</title>
		<link>http://www.weblimner.com/plugin/making-of-q-list-plugin-for-wordpres-2-of-2/</link>
		<comments>http://www.weblimner.com/plugin/making-of-q-list-plugin-for-wordpres-2-of-2/#comments</comments>
		<pubDate>Sat, 27 Mar 2010 22:16:21 +0000</pubDate>
		<dc:creator>Ali Sipahioglu</dc:creator>
				<category><![CDATA[Plugin]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[cookies]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[the_content]]></category>

		<guid isPermaLink="false">http://www.weblimner.com/?p=202</guid>
		<description><![CDATA[This is the second article of a series of articles explaining how I created the Q-List WordPress plugin. First article explained the administration section and this one will explain the user interface. This article consists of the following steps: Using tags in your posts like [qlist] Handling cookies for your plugin Handling forms Note: I [...]]]></description>
			<content:encoded><![CDATA[<p>This is the second article of a series of articles explaining how I created the Q-List WordPress plugin. First article explained the administration section and this one will explain the user interface. This article consists of the following steps:<br />
<br/></p>
<ul>
<li>Using tags in your posts like [qlist]</li>
<li>Handling cookies for your plugin</li>
<li>Handling forms</li>
</ul>
<p><span id="more-202"></span><br />
<br/><br />
<span class="important">Note: I am going to assume you read the first article and know the steps that are explained on creating the plugin.</span><br />
<br/><br />
First we are going to hook out function that handles showing the questions to the &#8220;content&#8221;. This will allow us to use te [qlist] tag to show the results and the poll.<br/></p>
<pre class="php">
add_filter('the_content', 'add_qlist_to_content');
</pre>
<p><br/><br />
Now we need to create out add_qlist_to_content function. This is a really simple function, it will get the $content variable only and depending on if the user has &#8220;posted&#8221; answers it will post answers to the database and also will show the questions and the results.<br />
<br/></p>
<pre class="php">
function add_qlist_to_content($content){
	if($_POST['qlistanswers']){
		post_answers();
	}
	if(preg_match_all("[qlist]",$content,$matches)){
                // Here I check if the [qlist] tag exists in the content of your post. $content is a variable that WordPress sends into your function.
		$content= str_replace("[qlist]",show_questions(),$content);
                // And if it exists I replace [qlist] with the return value from show_questions() and at the end of our function we return the $content
	}
	return $content;
}
</pre>
<p><br/></p>
<p><span class="important">If you don&#8217;t return the $content variable at the end of your function, you won&#8217;t see anything in your posts.</span><br />
<br/><br />
Now its time to show our questions. I kept this function seperate for those who wants to use it independently in their theme instead of using the [qlist] tag.<br />
<br/><br />
This function, like you probably have guessed, shows the questions and the results of your poll. The $listclass variable is also used in the function declaration, so that if anyone wants to use a different class name in the html, they can do so when calling the function. It is an optional variable.<br />
<br/></p>
<pre class="php">
function show_questions($listclass=''){
	global $wpdb;
	$user_id=$_SESSION['user_id']; // We get the current users session id for the cookies, which also will be used in the database.
	if($listclass==''){$listclass="qlist";} // I set the list class to qlist if the variable isn't set
	if(!isset($user_id)){$formclick = 'onclick="alert(\'You need to have cookies enabled to vote in your browser!\')"';}
        //Above is a check to see if the user has enabled cookies in their computer, othewise the plugin won't allow them to vote.
	$db_questions = $wpdb->get_results("SELECT * from ".$wpdb->prefix."qlists order by q_order,question");// Getting all the questions from our qlists table

	if(empty($db_questions)){return "";}// Check to see if there are no results return empty
	$qlist = '
<div class="graph"><a name="qlist" onclick="javascript:show_checked_qlist();">Switch View</a>';//This is to call jquery function that switches the view
	$qlist .= '
<form method="post" action="" '.$formclick.'>
<dl>';
	$qlist .= '';
		foreach ($db_questions as $db_question) {$i++;
			if($wpdb->get_var("Select count(a_id) from ".$wpdb->prefix."qlists_answers where u_id='$user_id' and q_id='".$db_question->q_id."' and answer='1'")){$isyes = ' checked="checked"';$uncheckedclass='';}else{$isyes='';$uncheckedclass='unchecked_qlist';}
			$qlist.='
<dt class="bar-title '.$uncheckedclass.'">
<input type="checkbox" name="box'.$db_question->q_id.'"'.$isyes.'/>';
			$qlist.=$db_question->question;
			$qlist .='<strong>'.$res.'</strong></dt>

';
			$res = get_qlist_result($db_question->q_id);
			$qlist .= '
<dd class="bar-container '.$uncheckedclass.'">
<div style="width:'.$res.'"></div>
</dd>

';
			$ids .= "$db_question->q_id,";
		}
		$qlist .= '
<dt class="bar-title">
<input type="hidden" value="'.$ids.'" name="qlistanswers"/>
<input type="submit" value="Save" /></dt>

';
		$qlist .= '</dl>
</form>
</div>

				';
	return $qlist;
}
</pre>
<p><br/><br />
There is one main loop in the function that loops through the resultset that the query returns from the table to prinout the questions and results. <br/></p>
<pre class="php">
if($wpdb->get_var("Select count(a_id) from ".$wpdb->prefix."qlists_answers where u_id='$user_id' and q_id='".$db_question->q_id."' and answer='1'")){$isyes = ' checked="checked"';$uncheckedclass='';}else{$isyes='';$uncheckedclass='unchecked_qlist';}
</pre>
<p><br/><br />
This checks if the user has answered yes to any of the questions and if they did, the checkbox is checked.<br />
<br/><br />
And the rest of the loop is basic php where we show the appropriate questions and answers. To show the percentages from the database for the results, I use a function that calculates it. Following line calls the function every time a question is printing out to the page and saves the result into the $res variable<br/></p>
<pre class="php">$res = get_qlist_result($db_question->q_id);</pre>
<p><br/></p>
<pre class="php">
function get_qlist_result($id){
	global $wpdb;
	$res = $wpdb->get_results("Select answer from ".$wpdb->prefix."qlists_answers where q_id='$id'");
	$a=$b=0;
	foreach ($res as $r) {
		if($r->answer=="1"){$a++;}
		$b++;
	}
	return number_format((($a/$b)*100),2)."%";
}
</pre>
<p><br/><br />
This function gets the question id from our &#8220;main&#8221; loop and looks in our answers table for all the answers that has the question id as the id that we&#8217;ve sent in. And then I loop through the result set and everytime the answer was true to the question i increment the counter &#8220;$a&#8221;, and also the number of results are saved into the counter &#8220;$b&#8221;. At the end I calculated the percentage by dividing a by b and then multiplying it by 100, hence getting percentage.<br />
<br/><br />
number_format is a function that only returns so many decimals after the comma so you won&#8217;t have ugly numbers like 14,333333333. Also I return the percentage sign at the end of our string so that can be used in showing the answer percentage.<br />
<br/><br />
Also a hidden input with all the ids from the questions are set in the &#8220;main&#8221; loop so that, they can be used in posting the answers to the database.<br />
<br/><br />
In our add_qlist_to_content function we had an if statement that checks if anything was posted. This function calls our post_answers() function.<br />
<br/><br />
This function gets the users current session id and also the results from the form that was posted and updates the answers table if the user is only changing his answers, or creates new records if this is users first time.<br />
<br/></p>
<pre class="php">
function post_answers(){
	global $wpdb;
	$user_id=$_SESSION['user_id'];
	if($user_id){
	$vars = $_POST;
	$i=0;
		while (list($key, $value) = each($vars)){
			if(preg_match("/box(\d+)/",$key)){
				$answers_checked[$i] = str_replace("box","",$key);
				$i++;
			}
		}
		$all_q = explode(",",$_POST['qlistanswers']);

		for($a=0;$a<(count($all_q)-1);$a++){
			if(in_array($all_q[$a],$answers_checked)){
				$answers[$a]["q_id"]=$all_q[$a];
				$answers[$a]["answer"] = "1";
			}else{
				$answers[$a]["q_id"]=$all_q[$a];
				$answers[$a]["answer"] = "0";
			}
		}

		for($a=0;$a<count($answers);$a++){
			if(!$wpdb->get_var("Select count(a_id) from ".$wpdb->prefix."qlists_answers where u_id='$user_id' and q_id='".$answers[$a]['q_id']."'")){
				$wpdb->insert($wpdb->prefix."qlists_answers",array('answer'=>$answers[$a]["answer"],'q_id'=>$answers[$a]["q_id"],'u_id'=>$user_id),array( '%d', '%d', '%s' ));
			}else{
				$wpdb->update($wpdb->prefix."qlists_answers",array('answer'=>$answers[$a]["answer"]),array( 'q_id' => $answers[$a]['q_id'],'u_id'=>$user_id ),array( '%d' ),array( '%d', '%s' ));
			}
		}
	}
}</pre>
<p><br/><br />
The &#8220;while&#8221; loop in our function gets the checked true questions into our array &#8220;answers_checked&#8221;. Then we loop throught the full question list that we&#8217;ve sent, in our hidden field to create a new array that has all the questions and also the answers called $answers. This is a multi-dimensional array.<br />
<br/><br />
Our final loop just loops through the answers array and updates or creates records depending on the user id. Our check in this line shows if the user has answered the question or not. Rest is update and insert statements that I explained in the first article that WordPress uses.</p>
<pre class="php">
if(!$wpdb->get_var("Select count(a_id) from ".$wpdb->prefix."qlists_answers where u_id='$user_id' and q_id='".$answers[$a]['q_id']."'")){
</pre>
<p><br/><br />
Now we also need to handle the users sessions so that we won&#8217;t lose them next time they come to the site. WordPress has a hook init that runs when the page is starting to load. This is run even before our plugin is run. We call a function set_userID_qlist() here.<br />
<br/><br />
This function first sets the expiration time for the cookie to be a year. Also we check if the sessions are already declared in our website if not we start the sessions. Then we check for the cookie user_id and if it is set, we save it into the session user_id. If it isn&#8217;t set then we create a unique id that starts with the string qid- and has random characters rest. uniqid is a php function which you can find information on php.net easily. Then we set the cookie user_id and also the session user_id<br />
<br/></p>
<pre class="php">
add_action('init', 'set_userID_qlist');

function set_userID_qlist(){
	$expire=time()+60*60*24*30*12;
	if(!session_id()){session_start();}
	if(isset($_COOKIE['user_id'])){
		$user_id=$_COOKIE['user_id'];
		$_SESSION['user_id']=$user_id;
	}else{
		$user_id = uniqid("qid-");
		setcookie("user_id", $user_id, $expire);
		$_SESSION['user_id']=$user_id;
	}
}
</pre>
<p><br/><br />
At this point your plugin will work fine but you styling won&#8217;t since we didn&#8217;t hook our stylesheet file to our plugin. To do so you need to use the wp_head action to call the function that registers and then prints the stylesheet. This function is self explanatory and there isn&#8217;t really much going on in it.<br />
<br/></p>
<pre class="php">
add_action('wp_head', 'add_qlist_styles');

function add_qlist_styles(){
	wp_register_style('qlist_create', WP_PLUGIN_URL.'/q-list-list-creator/q-list.css');
	wp_enqueue_style('qlist_create');
	wp_print_styles();
}
</pre>
<p><br/><br />
Also one last thing is to get our Switch View link to work. On click we made our link to call a javascript function named show_checked_qlist(). We need to create this function and hook it into our footer so that it printsout in the footer. This is a better practice to put javascript to the footer.<br/></p>
<pre class="php">
add_filter('wp_footer','add_qlist_js');

function add_qlist_js(){
	echo '<script type="text/javascript">
		function show_checked_qlist(){
			$(".unchecked_qlist").slideToggle("slow");
		}
	</script>';
}
</pre>
<p><br/><br />
<span class="important">You want to use jQuery selectors instead of using onclick events in the html. That is a whole article itself to be explained and is not in the scope of this one.</span><br />
<br/><br />
This concludes our plugin. Hope you liked it. Please let me know how you would have done this plugin or about your thoughts in the comments section. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.weblimner.com/plugin/making-of-q-list-plugin-for-wordpres-2-of-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making of Q-List Plugin for Wordpres &#8211; 1 of 2</title>
		<link>http://www.weblimner.com/tutorial/making-of-q-list-plugin-for-wordpres-1-of-2/</link>
		<comments>http://www.weblimner.com/tutorial/making-of-q-list-plugin-for-wordpres-1-of-2/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 03:35:30 +0000</pubDate>
		<dc:creator>Ali Sipahioglu</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[Plugin]]></category>
		<category><![CDATA[plugin naming]]></category>
		<category><![CDATA[version]]></category>
		<category><![CDATA[wordpress]]></category>
		<category><![CDATA[wpdb]]></category>
		<category><![CDATA[wp_options]]></category>

		<guid isPermaLink="false">http://www.weblimner.com/?p=193</guid>
		<description><![CDATA[This is the first article of a series of articles explaining how I created the Q-List WordPress plugin. First article will explain the administration section and the second will explain the user interface. This article consists of the following steps: Versioning your plugins database tables, and updating them Creating your administration interface Using wp options [...]]]></description>
			<content:encoded><![CDATA[<p>This is the first article of a series of articles explaining how I created the Q-List WordPress plugin. First article will explain the administration section and the second will explain the user interface. This article consists of the following steps:</p>
<ul>
<li>Versioning your plugins database tables, and updating them</li>
<li>Creating your administration interface</li>
<li>Using wp options table in your database for your plugin options</li>
</ul>
<p><span id="more-193"></span><br />
First we are going to start with the naming of our plugin. This step is really important if you want your plugin to work correctly. You need to name the folder same as your plugin’s file name. In our example we are going to name our plugin file q-list-list-creator.php and store it in q-list-list-creator. So our file structure is;<br/><br />
<img src="http://www.weblimner.com/wp-content/uploads/2010/2/filestructure.gif" alt="File" /><br/><br />
After you place the file under the right place, now it’s time for our comment section. If you don’t put this into your plugin, WordPress won’t know your file is a plugin. The following is the way I kept my plugins comment section, it&#8217;s pretty simple and yet keeps track of updates. For the full list of comments section, you can check <a href="http://codex.wordpress.org/Writing_a_Plugin" target="_blank">here</a>.<br/></p>
<pre class="php">/*
Plugin Name: Q-List
Plugin URI: http://www.weblimner.com/plugin/q-lists-list-creator/
Description: Create a list on your website and let members to vote the items of the list.
Author: Ali Sipahioglu
Author URI: http://www.weblimner.com
Version: 1.0
Change Log:
2010-30-01  1.0: In this version, users can vote without being a member of your website. Cookies are used. Design is changed. Percentages are shown for the results.
2010-20-01  0.6: Ability to see the results of the votes
2010-08-01  0.5: First release
*/</pre>
<p>The way the change log works is; you put your date first and then the version number and then briefly describe the updates you made. This is actually a good habit for when you go back to your code in the future, keeping track of an update and what it was.<br />
<br/><br />
<span class="important">Don&#8217;t forget to cover your whole file&#8217;s content with  tags.</span><br />
<br/><br />
At this point, WordPress will know the presence of your plugin, you will see it if you go to the wp-admin &gt; plugins.<br />
<br/><br />
Now we need to create the link to your plugin in your Settings menu. For that, create an action to hook your function to your admin menu. To do so;<br />
<br/></p>
<pre class="php">add_action('admin_menu', 'qlist_menu');</pre>
<p>qlist_menu is the function name that is going to create the menu item in your admin menu, so let&#8217;s create our qlist_menu function.</p>
<pre class="php">function qlist_menu(){
     add_options_page('Q-List Options', 'Q-List Options', 'administrator', 'qlist_unique', 'qlist_options');
}
</pre>
<p><br/><br />
Options are as follows;</p>
<ol>
<li>Title of your plugin in the administration.</li>
<li>Link that appears in the settings menu.</li>
<li>Capability required to see the menu link. In our case, you need to have administrator privileges to see it. You also have editor, author, contributor, subscriber options.</li>
<li>This has to be a unique name different from any plugin you might install to your WordPress installation so its better to keep your plugin name before it and then just but a string at the end like I did.</li>
<li>Name of the function that&#8217;s going to handle the administration view.</li>
</ol>
<p><br/>Now its time for your function.<br/></p>
<pre class="php">function qlist_options(){

}</pre>
<p><br/><br />
In our function we are going to use database calls so we need the database class of WordPress (<a href="http://codex.wordpress.org/Function_Reference/wpdb_Class" target="_blank">wpdb</a>). So lets add the following code to the first line of your function.</p>
<pre class="php">global $wpdb;</pre>
<p><br/>First we are going to create our form on the page.</p>
<pre class="php">$i=0;
echo '&lt;div class="wrap"&gt;
	 &lt;h2&gt;Q-List &lt;b&gt;Add New&lt;/b&gt;&lt;/h2&gt;
		 &lt;form method="post" action=""&gt;
		 &lt;table&gt;
			 &lt;tr&gt;
				&lt;th scope="row"&gt;Question&lt;/th&gt;
				&lt;td&gt;&lt;input type="text" name="question'.$i.'" size="60" /&gt;&lt;/td&gt;
				&lt;td&gt;Order: &lt;input type="text" name="order'.$i.'" size="5"/&gt;&lt;/td&gt;
			 &lt;/tr&gt;
			 &lt;tr&gt;
				 &lt;td colspan="3" align="center"&gt;
					 &lt;input type="hidden" name="addnewform" value="1"/&gt;
					 &lt;input type="submit" value="Save" /&gt;
				 &lt;/td&gt;
			 &lt;/tr&gt;
 ';
 echo     '&lt;/table&gt;&lt;/form&gt;';
 echo '&lt;h2&gt;Q-List &lt;b&gt;Edit&lt;/b&gt;&lt;/h2&gt;

 ';
 $db_questions = $wpdb-&gt;get_results("SELECT * from ".$wpdb-&gt;prefix."qlists order by q_order,question");
 foreach ($db_questions as $db_question) {$i++;
 echo
 '
 &lt;form method="post" action=""&gt;
	 &lt;table&gt;
		 &lt;tr&gt;
		 &lt;th scope="row"&gt;Question #'.($i-1).'&lt;/th&gt;
			 &lt;td&gt;&lt;input type="text" name="question" size="60" value="'.$db_question-&gt;question.'"/&gt;&lt;/td&gt;
			 &lt;td&gt;
			 Order: &lt;input type="text" name="order" size="5" value="'.$db_question-&gt;q_order.'"/&gt;
			 &lt;input type="hidden" name="updateform" value="'.$db_question-&gt;q_id.'"/&gt;
			 &lt;input type="submit" value="Update" /&gt;
			 &lt;a href="options-general.php?page=qlist_unique&amp;amp;delete='.$db_question-&gt;q_id.'" onclick="return confirm(\'You sure you want to delete?\');"&gt;Delete&lt;/a&gt;
			 &lt;/td&gt;
		 &lt;/tr&gt;
	 &lt;/table&gt;
 &lt;/form&gt;
 ';
 }

 echo     '&lt;/div&gt;';</pre>
<p>First part of our code only shows the empty form for a new step an admin might want to add. We set our action to nothing so when we submit it just comes back to the same page and then we query our database to see if there are any steps are already in. In our query we have &#8220;$wpdb-&gt;prefix&#8221; which creates that &#8220;wp_&#8221; in most cases that you have set when you set up your WordPress. And then its a foreach statement that goes through our array of results and prints them onto the page.<br />
<br/><br />
At this point besides our database updates, deletes, and adds our administration screen is set. Now its time to handle our form submissions.<br/></p>
<pre class="php">if($_POST['addnewform']){
 // Assign all the questions to an array
 $f_q= $HTTP_POST_VARS;
 for($a=0;$a&lt;((count($f_q)/2)-1);$a++){
	$form_questions[$a]["question"]=$_POST["question".($a+1)];
	$form_questions[$a]["order"]=$_POST["order".($a+1)];
 }
 // Get them into the database
 for($a=0;$a&lt;count($form_questions);$a++){
	 $wpdb-&gt;insert($wpdb-&gt;prefix."qlists",array('question'=&gt;$form_questions[$a]["question"],'q_order'=&gt;$form_questions[$a]["order"]),array( '%s', '%d' ));
 }
 }
 if($_POST['updateform']&gt;0){
	 $wpdb-&gt;update($wpdb-&gt;prefix."qlists",array('question'=&gt;$_POST['question'],'q_order'=&gt;$_POST["order"]),array( 'q_id' =&gt; $_POST['updateform'] ),array( '%s', '%d' ),array( '%d' ));
 }
 if($_GET['delete']){
	$wpdb-&gt;query("DELETE FROM ".$wpdb-&gt;prefix."qlists WHERE q_id = '".$_GET['delete']."'");
 }</pre>
<p>First if statement checks if it was a add new form by checking a hidden field that was set to 1 in our form. In our if statement I run through the array of post elements and save them into a multi-dimensional array and then I insert them into the WordPress database with the insert function. I am not going to explain how to do for loops in this article since I assume anyone that is creating a plugin for WordPress should know that much PHP. Now our insert function first gets the table name which is qlists with the prefix just like the way I explained earlier. Secondly it gets the an array for where you are going to put what so in our case its question that gets the question, q_order gets the order. And our last variable that we send in is an array that explains what type of data we are sending to each column in the database. &#8220;questions&#8221; is a string field so its %s and q_order is an integer field so its getting %d.  You can read more on this on the <a href="http://codex.wordpress.org/Function_Reference/wpdb_Class" target="_blank">wpdb</a> class page.<br />
<br/><br />
Next up is our update function. We update each step by itself, no loop going on here. All we do is check if it is an update form and if it is we update the database record. Only difference in this function is we need to tell what were going to update. In our case its determined by q_id that we got from the form and its an integer so we&#8217;ve set it at the end with %d.<br />
<br/><br />
That being said our administration section is done.<br />
<br/><br />
Now its time for our activation hook so that when someone activates/upgrades our plugin, our database is set up right. First we need to hook our function that is going to do that to the activation. We do this with the following code;<br />
<br/>
<pre class="php">register_activation_hook( __FILE__, 'qlist_activate' );</pre>
<p>Our function name is qlist_activate. Now its turn to create the function.</p>
<pre class="php">function qlist_activate() {
 global $wpdb;
 $qlist_db_version = "1.2";
 // Creating Questions Table
 $table_name = $wpdb-&gt;prefix . "qlists";
 if($wpdb-&gt;get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
	$sql = "CREATE TABLE " . $table_name . " (
	 `q_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
	 `question` VARCHAR( 250 ) NOT NULL ,
	 `q_order` INT NOT NULL
 );";

 // Creating Answers Table
 $answers_table_name = $wpdb-&gt;prefix . "qlists_answers";

 $sql .= "CREATE TABLE " . $answers_table_name . " (
	 `a_id` INT NOT NULL AUTO_INCREMENT  PRIMARY KEY ,
	 `q_id` INT NOT NULL ,
	 `u_id` CHAR ( 17 ) NOT NULL ,
	 `answer` INT NOT NULL
 );";
 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
 dbDelta($sql);

 }

 $client_qlist_db_version = get_option('qlist_db_version');
 if($client_qlist_db_version!=$qlist_db_version){
	$answers_table_name = $wpdb-&gt;prefix . "qlists_answers";
	 $sql_up = "CREATE TABLE " . $answers_table_name . " (
	 `a_id` INT NOT NULL AUTO_INCREMENT  PRIMARY KEY ,
	 `q_id` INT NOT NULL ,
	 `u_id` CHAR ( 17 ) NOT NULL ,
	 `answer` INT NOT NULL
 );";
 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
 dbDelta($sql_up);
 }

 add_option("qlist_db_version", $qlist_db_version); // If the database is ever needed to be updated
}</pre>
<p>We are going to do a database connection again so we need our global $wpdb in the first line. And right after that we&#8217;ve set up the version of our database.<br />
<br/><br />
First we create the table that is going to hold the questions in our list. We set the table name with the wpdb prefix with $table_name = $wpdb-&gt;prefix . &#8220;qlists&#8221;;<br />
<br/><br />
Now we check if the table is already created by just doing a show table statement in the database looking for our table name and if its not set we add our sql statement to create our table into a variable ($sql). Right after that we set the name for our answers table into a variable. Then we create an sql statement for that table and append that to our current $sql variable. Now the following two lines are important for versioning your database in WordPress. You need to call the upgrade.php file and then send your $sql into a function called dbDelta like I did in our example. This is fine if you are not planning on making any changes to your database in the future, which is probably not the case since there always is a change you might need.<br />
<br/><br />
Now we get the current version of our database if it is already set up with $client_qlist_db_version = get_option(&#8216;qlist_db_version&#8217;);<br />
<br/><br />
get_option is a function that gets an option that is set up in the WordPress options table in your database. You can use that table for other data too. Ill show you how to set data into that table on the last line of our activation function.<br />
<br/><br />
Now we compare our version of the tables to the version of our tables that are currently set. If an upgrade is needed we again create our sql statement that would create the table from scratch. Rest is simple, we call our upgrade file in and send our sql line to dbDelta function<br />
<br/><br />
NOTE: DO NOT CREATE AN UPGRADE STATEMENT, it should be a create table statement.<br />
<br/><br />
Now to create the option that is going to set the current db version into the WordPress options table; all you need to do is the following code;<br />
add_option(&#8220;qlist_db_version&#8221;, $qlist_db_version);<br />
<br/><br />
That concludes our administration section of our plugin. You can download the most current version of the plugin from <a href="http://wordpress.org/extend/plugins/q-lists-list-creator/">WordPress repository</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.weblimner.com/tutorial/making-of-q-list-plugin-for-wordpres-1-of-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk (enhanced)
Object Caching 317/352 objects using disk

Served from: www.weblimner.com @ 2012-02-06 03:14:56 -->
