<?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>Inside DealTaker &#187; db</title>
	<atom:link href="http://www.dealtaker.com/blog/tag/db/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dealtaker.com/blog</link>
	<description>All Things Deal Oriented</description>
	<lastBuildDate>Fri, 20 Nov 2009 21:47:05 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Kohana PHP Tuturial &#8211; Part III</title>
		<link>http://www.dealtaker.com/blog/2009/06/19/kohana-php-tuturial-part-iii/</link>
		<comments>http://www.dealtaker.com/blog/2009/06/19/kohana-php-tuturial-part-iii/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 13:26:09 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[technology]]></category>
		<category><![CDATA[db]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=1013</guid>
		<description><![CDATA[It&#8217;s been a couple weeks now, so lets get back on track with this series of tutorials. This tutorial will get into models and how to play with data.

The first thing I have to is tell you is that Kohana PHP has been updated since the last tutorial. So I have gone ahead and took [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a couple weeks now, so lets get back on track with this series of tutorials. This tutorial will get into models and how to play with data.<br />
<span id="more-1013"></span></p>
<p>The first thing I have to is tell you is that Kohana PHP has been updated since the last tutorial. So I have gone ahead and took the last tutorial and updated the core and made sure it worked with Kohana 2.3.4. <a href="http://images.dealtaker.com/dealtaker/blog/kohana/dealtaker-kohana-2-2.3.4.zip">You can grab that here</a>. Now onward to the glory!</p>
<p>The first thing we want to do is identify where and what the data is. Is it an XML feed, CSV, JSON, DB or something else? Well I&#8217;m going to make it easy. We are going to deal with our friend MySQL for this. The next step is to setup a MySQL DB connection.</p>
<p>Go into your system/config folder and copy the database.php file to your application/config folder. Edit the application/config/database.php to reflect your server settings. Mine looks like this:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">$config['default'] = array
(
	'benchmark'     =&gt; TRUE,
	'persistent'    =&gt; FALSE,
	'connection'    =&gt; array
	(
		'type'     =&gt; 'mysql',
		'user'     =&gt; 'root',
		'pass'     =&gt; 'root',
		'host'     =&gt; 'localhost',
		'port'     =&gt; FALSE,
		'socket'   =&gt; FALSE,
		'database' =&gt; 'myfirstkohana'
	),
	'character_set' =&gt; 'utf8',
	'table_prefix'  =&gt; '',
	'object'        =&gt; TRUE,
	'cache'         =&gt; FALSE,
	'escape'        =&gt; TRUE
);</pre>
<p>Now that we have a configuration a connection for our database, we should probably set up a database and a table. Here&#8217;s the SQL:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`myfirstkohana` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `myfirstkohana`;

/*Table structure for table `posts` */
DROP TABLE IF EXISTS `posts`;

CREATE TABLE `posts` (
  `id` mediumint(8) unsigned NOT NULL auto_increment,
  `title` varchar(255) default NULL,
  `post` text,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;

/*Data for the table `posts` */
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;</pre>
<p>This is a pretty straight forward &#8220;Create a DB and one table&#8221; setup. You might notice that we have everything set for UTF8. This will match the DB configuration setting and also will allow us to deal with i18n (Internationalization) stuff later on.</p>
<p>Onward to creating an actual model. There are a couple things to keep in mind with naming conventions, well really one. From the docs &#8220;The model class name is capitalized, does have _Model appended to it and should be the singular form of the name.&#8221;. There are so other rules when you are dealing with ORM, but we won&#8217;t be dealing with ORM in this tutorial.</p>
<p>Create a file named post.php in the &#8216;application/models/&#8217; folder and make it look like the following:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">&lt;?php
defined('SYSPATH') or die('No direct script access.');

class Post_Model extends Model
 {
    public function __construct()
    	{
		      parent::__construct();
    	}

 }</pre>
<p>As you can tell the above really doesn&#8217;t do much, so let&#8217;s give it some functionality:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">&lt;?php
defined('SYSPATH') or die('No direct script access.');

class Post_Model extends Model
 {
    public function __construct()
    	{
		      parent::__construct();
    	}

    public function getPosts()
     {
        $sql = 'SELECT *
                FROM   `posts`
                LIMIT  0, 10';

        return $this-&gt;db-&gt;query($sql);
     }
 }</pre>
<p>So we have a model method that pulls 10 posts from the table with a pretty simple query. We use &#8220;$this-&gt;query()&#8221; to run queries, which will return object and we return that to the calling entity. Check the query method <a href="http://docs.kohanaphp.com/libraries/database/query" target="_blank">docs here</a> for more information.</p>
<p>Let&#8217;s update our &#8216;Hello&#8217; controller to use this the model.</p>
<p>In your application/controllers/hello.php update your index() method to look like this:</p>
<pre>    public function index()
     {
        // Load the models
        $post  = new Post_Model;
        $posts = $post-&gt;getPosts();
        $rpsts = "";

        // Loop thru the posts
        foreach($posts-&gt;result_array(FALSE) as $row)
         {
          // Simple output of
          $rpsts .= '
    &lt;h1&gt;'.$row['title'].'&lt;/h1&gt;
    '.$row['post'].'&lt;hr /&gt;';
         }

        // Put something useful in our variables.
        $this-&gt;template-&gt;header-&gt;pageTitle .= ' ::: I am on the top';
        $this-&gt;template-&gt;content-&gt;content   = $rpsts;
     }</pre>
<p>When we run the hello controller, we won&#8217;t get much but &#8216;This is my second view&#8217;. We need to put stuff in the table. Use your favorite method of accessing your DB and insert some rows. Now when you run it you will see stuff!</p>
<p>If you notice there is a &#8220;$post-&gt;result_array()&#8221; inside a foreach loop. This allows us to loop though the results of the query easily from within the controller.</p>
<p>You might have notice something of bad practice. I pretty much created HTML inside the controller. As we all know, we shouldn&#8217;t do this. Let&#8217;s fix this!</p>
<p>Create a new view named main_posts.php and make it look like:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">&lt;?php foreach($posts as $post): ?&gt;
&lt;h1&gt;&lt;?php echo $post['title'];?&gt;&lt;h1&gt;
&lt;?php echo $post['post'];?&gt;&lt;hr /&gt;
&lt;?php endforeach; ?&gt;</pre>
<p>This view does a foreach on our query results and fills in our little view.</p>
<p>In the the index method of our controller we will need to change up the controller to use our new view.</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">   public function index()
     {
        // Load the models
        $post  = new Post_Model;
        $posts = $post-&gt;getPosts();

        // Put something useful in our variables.
        $this-&gt;template-&gt;header-&gt;pageTitle .= ' ::: I am on the top';

        // Posts view
        $this-&gt;template-&gt;content-&gt;content        = new View('main_posts');
        $this-&gt;template-&gt;content-&gt;content-&gt;posts = $posts-&gt;result_array(FALSE);
     }</pre>
<p>As you can tell, it&#8217;s pretty simple and it&#8217;s clean! Here&#8217;s a quick sample on how to do an insert. We are going to add a method to the post model called addPost.</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">  public function addPost($title, $post)
    {
       $sql = sprintf('INSERT INTO `posts`
                       SET         `title` = %s,
                                   `post`  = %s',
                       $this-&gt;db-&gt;escape($title),
                       $this-&gt;db-&gt;escape($post));
      $this-&gt;db-&gt;query($sql);
    }</pre>
<p>We need to add a method to handle adding of posts to our hello controller:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">   public function addpost()
     {
        // Load the models
        $post  = new Post_Model;
        $post-&gt;addPost($_POST['title'], $_POST['post']);
        url::redirect('hello');
     }</pre>
<p>And lets add a form to the end of the main_post.php in the views:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">&lt;form method="POST" action="&lt;?php echo url::base();?&gt;hello/addpost/"&gt;
  &lt;table&gt;
    &lt;tr&gt;
     &lt;th&gt;
       Title
     &lt;/th&gt;
     &lt;th&gt;
       Post
     &lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
     &lt;td&gt;
      &lt;input type="text" name="title" /&gt;
     &lt;/td&gt;
     &lt;td&gt;
      &lt;textarea cols="20" rows="5" name="post"&gt;&lt;/textarea&gt;
      &lt;input type="submit" name="submit" value="Submit"/&gt;
     &lt;/td&gt;
  &lt;/table&gt;
&lt;/form&gt;</pre>
<p>Once again, pretty simple right? I could go on and give you how to edit entries, but I&#8217;m leaving that to you for your home work. Free free to post your results! Until next time when will go over libraries and helpers, keep on coding till your fingers bleed!</p>
<p><a href="http://images.dealtaker.com/dealtaker/blog/kohana/dealtaker-kohana-3.zip">Get the file for this tutorial here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/blog/2009/06/19/kohana-php-tuturial-part-iii/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
