<?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>Greymass - Exploring Everything &#187; PHP</title>
	<atom:link href="http://www.greymass.com/category/programming/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.greymass.com</link>
	<description>Web Development, Design, PHP and random musings</description>
	<lastBuildDate>Wed, 25 Aug 2010 16:22:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>ZF-Starter, the &#8220;Zend Framework &#8211; Starter Kit&#8221;</title>
		<link>http://www.greymass.com/zf-starter-the-zend-framework-starter-kit/</link>
		<comments>http://www.greymass.com/zf-starter-the-zend-framework-starter-kit/#comments</comments>
		<pubDate>Mon, 23 Aug 2010 18:25:46 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[ZF-Starter]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[zend-framework]]></category>
		<category><![CDATA[zf-starter]]></category>

		<guid isPermaLink="false">http://www.greymass.com/?p=202</guid>
		<description><![CDATA[It&#8217;s been a while since I&#8217;ve written a blog post because I&#8217;ve been extremely tied up with projects at work up for the last year+. However, now comes a time when I want to go back, explore what I&#8217;ve learned, and in the process develop a short set of tutorials explaining it all. The tools [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while since I&#8217;ve written a blog post because I&#8217;ve been extremely tied up with projects at work up for the last year+. However, now comes a time when I want to go back, explore what I&#8217;ve learned, and in the process develop a short set of tutorials explaining it all. The tools and code that I post up are going to be used in my everyday work, things I find useful and even things to make my personal coding experience easier (hopefully yours too).</p>
<p>The first part of this series will focus solely on downloading the starter kit, how to pull it down from the SVN, and how to make sure your apache is configured to handle it. The rest of the series will focus on using this starter kit to make some awesome apps.</p>
<p>To start with, this series will assume that you have a basic knowledge of the following:</p>
<ul>
<li>Configuring your own local apache test environment or using a live apache server.</li>
<li>Basic understanding of PHP syntax, functions and usage.</li>
<li>Some knowledge of OOP, understanding of classes and methods.</li>
</ul>
<p>Basically I will be giving you a &#8220;Starter Kit&#8221;, which will require you to have a functional PHP/Apache setup in order to run. From here on out, instead of referring to the package as the &#8220;Zend Framework Starter Kit&#8221;, I will simply be calling it <strong>ZF-Starter</strong>. You are free to use this code however you see fit, without attribution! Read on to check out all the steps in getting the code and getting started!</p>
<p><span id="more-202"></span></p>
<h2><strong>Exporting your copy of ZF-Starter</strong></h2>
<p>For ease of updating on my part, and since most developers already use some form of <a href="http://en.wikipedia.org/wiki/Revision_control" target="_blank">Version Control</a>, I&#8217;ve added a public <a href="http://en.wikipedia.org/wiki/Apache_Subversion" target="_blank">SVN Repository</a> to greymass.com that contains a &#8220;Zend Framework Starter Kit&#8221;. If you are unfamiliar with using a SVN, I would like to direct you to a <a href="http://www.smashingmagazine.com/2009/03/10/ultimate-round-up-for-version-control-with-subversion/" target="_blank">Round-Up post on Smashing Magazine with SVN resources</a>. It&#8217;s a little older, but the resources within are still valid and good for learning about source control with SVN.</p>
<p>So, before you download the code itself, we should probably talk about how Apache or your Web Server needs to be configured in order to run this sample code. I will list off some of the basics that you need to have setup/enabled:</p>
<ul>
<li><a href="http://www.google.com/search?q=enable+mod_rewrite" target="_blank">Enable apache&#8217;s mod_rewrite</a> (or your web server&#8217;s equivalent extension)</li>
<li>PHP 5.3+ (5.2.x for earlier tutorials, but we will get into some things that require 5.3, so upgrading is recommended)</li>
<li><a href="http://php.net/manual/en/ini.core.php" target="_blank">Enable PHP&#8217;s short_open_tag</a> in your php.ini or .htaccess</li>
<li>The DocumentRoot for running this example will be the <strong>/public_html </strong>folder within the repository, not the root.</li>
<li>You will need your web server setup to use the <strong>.htaccess </strong>included within the /<strong>public_html </strong>folder.</li>
</ul>
<p>If anyone has any specific questions or setup problems with setting up their instance of a web server, I&#8217;d like to direct you to <a href="http://serverfault.com" target="_blank">ServerFault.com</a>. I really want to focus on the actual implementation of Zend Framework and less on the millions of configurations web servers can have. Onto the repository!</p>
<p><strong>ZF-Starter Repository URL: </strong><strong><a href="http://greymass.com/code/zf-starter" target="_blank">http://greymass.com/code/zf-starter</a></strong></p>
<p>Once you have some form of SVN installed on the operating system of your choice, there are 2 methods that you can download the ZF-Starter Kit. Both methods I will recommend use the &#8220;Export&#8221; feature of SVN, which will download the code and remove the &#8220;Version Control&#8221; from the code. You could also simply do a &#8220;Check Out&#8221; of this code, however if you started making changes, you&#8217;d be unable to commit them back to my public repository, so really checking out isn&#8217;t needed.</p>
<ul>
<li><strong>SVN Export (Command Line) </strong>- If you are running from a command line, you can download the code from this command:</li>
<li>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">svn export http://greymass.com/code/zf-starter c:/path/to/your/web/folder</pre></div></div>

</li>
</ul>
<ul>
<li><strong>SVN Export (GUI)</strong></li>
<li>Windows/TortoiseSVN: Right click in the folder you wish to download the code. On the menu that pop&#8217;s up, hover over &#8220;Tortoise SVN&#8221; and on the sub-menu, click &#8220;Export&#8221;. The first box, &#8220;URL of the Repository&#8221; on the export screen should be the repository URL located above.</li>
</ul>
<p style="text-align: center;"><img class="aligncenter" title="Tortoise Menu" src="http://www.greymass.com/wp-content/uploads/2010/08/Screen-shot-2010-08-23-at-11.17.58-AM.png" alt="" width="365" height="358" /></p>
<p style="text-align: left;">After the export is complete, browse to the folder that you downloaded, it should look something like this:</p>
<p><img class="aligncenter size-full wp-image-219" title="Screen shot 2010-08-23 at 12.48.45 PM" src="http://www.greymass.com/wp-content/uploads/2010/08/Screen-shot-2010-08-23-at-12.48.45-PM.png" alt="" width="301" height="360" /></p>
<h2><strong>What are all these folders?</strong></h2>
<p>The starter kit is all about organization and establishing the base hierarchy of what you will be building. There are a few different ways you can use and implement the Zend Framework, this method is using the <a href="http://en.wikipedia.org/wiki/Model–View–Controller" target="_blank">MVC pattern</a>. The 2nd section of the <a href="http://framework.zend.com/manual/en/learning.quickstart.intro.html" target="_blank">Zend Framework &#8211; Quick Start</a> gives a nice short overview of what these pieces do. Here&#8217;s a quick breakdown in my own words:</p>
<ul>
<li><strong>Controllers &#8211; </strong>Controllers are objects that parse user input, call upon the models the user may need, redirect the user to a view and control the flow of traffic.</li>
<li><strong>Models &#8211; </strong>The model is the &#8220;data&#8221; object, the source of your information. MySQL tables can be used in models to fetch and store data, along with many other DB/NoDB solutions (which we will get into later in the series)</li>
<li><strong>Views &#8211; </strong>In one word: Templates. These are the files that hold your HTML, fill in the actual pages, and know how to display the data that the user has requested.</li>
</ul>
<p>As you can see in the ZF-Starter, these are all folders with the <strong>/application</strong> folder. The other two folders not mentioned in the MVC structure that are included in the <strong>/applications</strong> folder are the <strong>layouts </strong>and <strong>configs</strong> folders. The <strong>layouts </strong>folder is a <em>view</em> technically, as it is used to create generic templates used site-wide, which will be used later in this series. The <strong>configs </strong>folder is probably a little more simple, it&#8217;s basically a location to store your server-based configuration options for your application (ie your DB connection string, analytics code, etc).</p>
<p>Also included as a folder you will find the <strong>/library</strong> and <strong>/scripts </strong>folders. The <strong>/library</strong> folder contains the Zend Framework as well as any other libraries you may require and/or create. The <strong>/scripts </strong>folder is a utility folder, which I use to store shell scripts/batch files to automate some routine tasks. For now, we will leave these folders alone, and come back to them later.</p>
<p>The last folder included is the <strong>/public_html </strong>folder, which is exactly what it sounds like, the root of your website. Images, Stylesheets, Javascript and all other files that aren&#8217;t part of your code can be placed in here just like any other website. The <strong>index.php </strong>and <strong>.htaccess </strong>files are already configured in those folders to run the site, and should need very little modifications for basic usage.</p>
<h2>So what needs to be done?</h2>
<p>The only thing that needs to be done after Apache is configured and the code is placed in the proper location is one step: rename the configuration file. In the folder <strong>/application/configs/</strong> you will find a file named <strong>application.ini.template</strong>. This file just needs to be renamed to <strong>application.ini</strong>. Take a look in the file if you want to see some common configuration options, we will be changing this file in the future to add more flexibility to the application.</p>
<p>After you rename/copy your application.ini, try loading up the site and you should see the following (with a different time obviously):</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-220" style="border: 1px solid black;" title="Screen shot 2010-08-23 at 1.18.09 PM" src="http://www.greymass.com/wp-content/uploads/2010/08/Screen-shot-2010-08-23-at-1.18.09-PM.png" alt="" width="512" height="173" /></p>
<p>That&#8217;s pretty much it&#8230; throughout this small tutorial you should have completed the following steps.</p>
<ul>
<li>1) Have a functional Apache/IIS configuration with a mod_rewrite compatible extension.</li>
<li>2) Check-Out / Export the ZF-Starter Kit onto your local machine/web server.</li>
<li>3) Configure Apache/IIS site to point the DocumentRoot to the /public_html folder.</li>
<li>4) Rename/Copy the application.ini.template file to application.ini.</li>
<li>5) Check your site via a browser and see a page with some examples and the current time.</li>
</ul>
<p>I plan (time permitting) on creating an entire series of &#8220;How-To&#8217;s&#8221; based on this ZF-Starter kit explaining how to integrate Databases, Frameworks and other libraries into the mix, if you have any requests, or end up creating anything cool with the kit, feel free to drop a comment and let me know!</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.greymass.com/zf-starter-the-zend-framework-starter-kit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ADOdb&#8217;s Active Record Implementation and Data Dictionary in PHP</title>
		<link>http://www.greymass.com/adodbs-active-record-implementation-and-data-dictionary-in-php/</link>
		<comments>http://www.greymass.com/adodbs-active-record-implementation-and-data-dictionary-in-php/#comments</comments>
		<pubDate>Wed, 13 May 2009 20:35:32 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[ADOdb]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[ActiveRecord]]></category>
		<category><![CDATA[database schema]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[functionality]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[xml schema]]></category>

		<guid isPermaLink="false">http://www.greymass.com/?p=166</guid>
		<description><![CDATA[The Active Record Pattern is a method developed to help access and store data in relational databases. This small post will cover some of the basic Active Record methods that you can use with the <a href="http://adodb.sourceforge.net/">ADOdb Library</a> in PHP. When used properly, the Active Record Pattern can help you develop and visualize your data faster than just throwing database queries into your applications. ]]></description>
			<content:encoded><![CDATA[<p>The Active Record Pattern is a method developed to help access and store data in relational databases. This small post will cover some of the basic Active Record methods that you can use with the <a href="http://adodb.sourceforge.net/">ADOdb Library</a> in PHP. When used properly, the Active Record Pattern can help you develop and visualize your data faster than just throwing database queries into your applications.<br />
<span id="more-166"></span><br />
Here is a quote from Wikipedia detailing exactly what the Active Record Pattern is:</p>
<blockquote><p><strong>From: <a href="http://en.wikipedia.org/wiki/Active_record_pattern">Wikipedia on the Active Record Pattern</a></strong><br />
<em>Active record is an approach to access data in a database. A database table or view is wrapped into a class, thus an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database; when an object is updated, the corresponding row in the table is also updated. The wrapper class implements accessor methods or properties for each column in the table or view.</em></p></blockquote>
<p>Essentially what we are doing is building a class for our tables in our database, then using the objects created to control what is coming in and out of the database. Also, for this post, I am going to be referencing the same contact table that was created and covered in our first ADOdb post, <a href="http://www.greymass.com/getting-started-with-adodb-for-php/">Getting started with ADOdb for PHP</a>. Now, not to worry if you do not have the database already created, because in this article we also are going to cover dynamically generating table schema with XML using the ADOdb Data Dictionary. </p>
<p>To get started, lets first write the class that will control our contacts table.</p>
<h2>An ADOdb_Active_Record Class</h2>
<p>Each one of our tables that we want to access via the Active Records Method needs a class wrapped around it. The class we are going to create is going to be called <strong>contact</strong> and will extend the <em>ADOdb_Active_Record</em> class. The extending of the ADOdb class will give us all the basic functionality we will need in our class. You also will need to include one more file into your header, as well as change the way your database adapter is called.</p>
<pre name="code" class="php">
require_once("adodb/adodb.inc.php");
require_once('adodb/adodb-active-record.inc.php');
$db = NewADOConnection($config['dbtype']);
$db->debug = true;
$db->Connect($config['server'], $config['username'], $config['password'], $config['database']);
ADOdb_Active_Record::SetDatabaseAdapter($db); // This line of code establishes DB connection to work with ActiveRecords.
</pre>
<p>Now lets make an extremely simple table wrapper class.</p>
<pre name="code" class="php">
class contact extends ADOdb_Active_Record{
	var $_table = 'contacts'; // We need to specify what the name of the table is for this class.
}
</pre>
<p>It&#8217;s pretty simple, nothing here is required of the class, except for the $_table variable, and that is only required if your table name differs from the name of the class. Since the name of our class is <strong>contact</strong> and the table is named <strong>contacts</strong>, we must specify what the table is named. </p>
<p>Organizing how you wish to place your classes and files is up to you, but if you are looking for ideas, here is the generic directory structure that I use to setup my project. </p>
<pre name="code" class="php">
   project/
      db/
         wrappers/
            contact.php
         schemas/
            contact.xml
      index.php
</pre>
<p>The wrappers folder contains all of the classes for the tables, while the schemas folder contains all of the XML files used to build/maintain the databases. However, for this example, I am just going to leave them all in the same file or same folder. </p>
<h2>Building a method to Maintain our Schema</h2>
<p>This is a small method I normally include in all of my wrappers to build the databases. You could easily build a class of your own that the wrappers extend, then have your new class extend the ADOdb class, to prevent yourself from repeating code. However, in this example, we are going for simplicity and keeping everything in one place and making it work. First off you are going to need to include the proper files from ADOdb, including adodb/adodb-xmlschema.inc.php. This file is the file that will do the parsing and execution of the XML files you will create.</p>
<p>So, now lets make an XML Schema file that will control the format of our table. </p>
<pre name="code" class="php">
&lt;?xml version="1.0"?&gt;
&lt;schema version="0.2"&gt;
  &lt;table name="contacts"&gt;
    &lt;field name="id" type="I"&gt;
      	&lt;descr&gt;A unique ID assigned to each contact.&lt;/descr&gt;
      	&lt;KEY/&gt;
      	&lt;AUTOINCREMENT/&gt;
    &lt;/field&gt;
    &lt;field name="FirstName" type="C" size="50"&gt;
				&lt;NOTNULL/&gt;
		&lt;/field&gt;
    &lt;field name="LastName" type="C" size="50"&gt;
    		&lt;NOTNULL/&gt;
    &lt;/field&gt;
    &lt;field name="Phone" type="C" size="15"&gt;
    		&lt;NOTNULL/&gt;
    &lt;/field&gt;
    &lt;field name="Email" type="C" size="100"&gt;
    		&lt;NOTNULL/&gt;
    &lt;/field&gt;
  &lt;/table&gt;
&lt;/schema&gt;
</schema>
</pre>
<p>The layout of the XML is pretty easy to understand if you just glance over it. Essentially it is the schema of our database written out in a simple to use XML format. Each table and each field receives its own nodes and parts of the XML. More documentation on exactly what you can include into this XML can be found in the <a href="http://phplens.com/lens/adodb/docs-datadict.htm">Data Dictionary Documentation</a>, about 1/2 way down the page. You are going to need to save this file in the same area that you are working in, I saved it as <strong>contacts.xml</strong>.</p>
<h2>Building an Initialization Method for the Schema</h2>
<p>Now that we have our XML written for the table, now we need to parse it and include it into our table. For this, I normally would make a method called &#8220;init&#8221; on my wrapper that calls the proper XML file, parses it and executes any updates needed to the table all while maintaining the data within the table. Here is what our table wrapper would look like with this class embedded in it.</p>
<pre name="code" class="php">
class contact extends ADOdb_Active_Record{
	var $_table = 'contacts'; // We need to specify what the name of the table is for this class.

	// This is a function I created, to work with the XML DB schema
	function init() {
		global $db; // We need to bring in the $db adapter
		$schemaFile = "contacts.xml"; // This is the file of the schema
		$schema = new adoSchema($db); // Establish a new Schema Object, and pass in the DB parameters
		$schema->ParseSchema($schemaFile); // Parse through the schema and read it into the object
		$schema->ExecuteSchema(); // Execute the Schema, and update the table if needed
	}
}
</pre>
<p>The code above is pretty well commented, essentially we are telling the object which file it should be using as its schema, creating a new schema object, parsing the schema then executing any actions required to update the table. If the script you were running had to build tables on the fly, this might be an excellent way to accomplish it. The main reason I use these XML schema is for rapid deployment across multiple servers. No more porting data from one database server to another, instead have an init call that will build your tables for you. </p>
<p>Alright, now that the wrapper object is created, we can move into the actual application portion of the code. So far, if you are using the code from the last example, your code should look something like this.</p>
<pre name="code" class="php">
require_once("adodb/adodb.inc.php");
require_once('adodb/adodb-active-record.inc.php');
require_once("adodb/adodb-xmlschema.inc.php");

$config['server'] = "localhost";
$config['dbtype'] = "mysql";
$config['username'] = "root";
$config['password'] = "";
$config['database'] = "adodb_test";  

$db = NewADOConnection($config['dbtype']);
$db->debug = true;
$db->Connect($config['server'], $config['username'], $config['password'], $config['database']);

// This line of code establishes DB connection to work with ActiveRecords.
ADOdb_Active_Record::SetDatabaseAdapter($db);

// This is a special class for your table, extending the ADOdb_Active_Record class.
class contact extends ADOdb_Active_Record{
	var $_table = 'contacts'; // We need to specify what the name of the table is for this class.

	// This is a function I created, to work with the XML DB schema
	function init() {
		global $db; // We need to bring in the $db adapter
		$schemaFile = "contacts.xml"; // This is the file of the schema
		$schema = new adoSchema($db); // Establish a new Schema Object, and pass in the DB parameters
		$schema->ParseSchema($schemaFile); // Parse through the schema and read it into the object
		$schema->ExecuteSchema(); // Execute the Schema, and update the table if needed
	}
}</pre>
<p>This is all of the code you should need to get started working with the contacts table, besides the contacts.xml file which we covered in the last section. Now, anytime you need to recreate the table or update the schema of the contacts table, you need to call 2 lines of code.</p>
<pre name="code" class="php">
// First off, we create a new instance of the contacts table wrapper object
$contact = new Contact();
// Then, if needed, we run the init() command to create/update the table as the schema sees fit.
$contact->init();
</pre>
<p>If you have debugging on, you will see the SQL commands the Active Records method is going to generate automatically for you. You could add or remove columns, modify data types, or even rename columns from the XML, and once these lines of code execute, it will correct your table to match the schema. This is <strong>incredibly</strong> useful when you are developing an application across multiple servers and need to ensure that the database schemas across all development platforms are the same structure. </p>
<h2>Inserting a new record into the Contacts Table</h2>
<p>Well, running the above code should give you the table at least, you may want to insert some dummy records into the table, so lets show you how to create a new record in the table.</p>
<pre name="code" class="php">
// Lets insert a new record from scratch
$newPerson = new Contact();
// Set all of their values for the database
$newPerson->firstname = "Aaron";
$newPerson->lastname = "Cox";
$newPerson->phone = "555-012-3456";
$newPerson->email = "aaroncox@emailaddress.com";
// And finally save the person in a new record
$newPerson->save();
// Wondering what their Database ID was? Well it autopopulates it into the field upon saving.
echo $newPerson->id;
// Echoing the $newPerson->id will display their new ID on the page.
</pre>
<p>All we have to do to create a new table record is create a new instance of the Active Record class, and start populating the properties of the object. Once complete, call the ->save() method on the object and poof, your record is properly saved into the database. The object is also updated with the proper ID that was auto generated by the table, you can see this on the last 2 lines of the example above, as I am echoing the content out to the screen.</p>
<p>When I started with Active Records, using this method helped me a tremendous amount when trying to figure out what variables I was setting to what values. Reading code like this is so extremely simple and effective. </p>
<h2>Populating an Active Record by ID</h2>
<p>Another incredibly useful method you can use with Active Records is to load records, then update them. To load a record, you simply use 1 line of code.</p>
<pre name="code" class="php">
$contact->load("id = 1");
$contact->firstname = "ChangedName";
$contact->save();
</pre>
<p>The first line will run the SQL query and load ID = 1 into the object, making it look something like this:</p>
<pre name="code" class="php">
contact Object
(
    [_table] => contacts
    [_dbat] => 0
    [_tableat] => contacts
    [_where] => id = 1
    [_saved] => 1
    [_lasterr] =>
    [_original] => Array
        (
            [0] => 1
            [1] => Joe
            [2] => User
            [3] => 545-454-5454
            [4] => joe@joeuser.com
        )

    [id] => 1
    [firstname] => Joe
    [lastname] => User
    [phone] => 545-454-5454
    [email] => joe@joeuser.com
)
</pre>
<p>You can do this via any search method you can use in SQL as well, here are a few examples. Keep in mind however that the &#8220;LOAD&#8221; method will only return one record. After the record was loaded, I am changing the firstname value to &#8220;ChangedName&#8221; and then proceeding to save the record. Once again, with debugging on, you will see the library writing the SQL for you to update that record to the value you chose to set it to.</p>
<p>Here are a few more examples of ways you can load data using the load method.</p>
<pre name="code" class="php">
$contact->load("firstname = 'John'"); // Finds all with firstname IS John
$contact->load("firstname like 'John%'"); // Finds all with firstname LIKE John%
$contact->load("firstname like 'John%'"); // Finds all with firstname LIKE John%
</pre>
<h2>Returning an Array of Objects using FIND</h2>
<p>If you want to return multiple results into an array of objects, you can use the find method to do so. Find functions the same way as load, except it returns the values back into the array specified. We are going to use the same examples above, except as arrays with multiple objects inside them.</p>
<pre name="code" class="php">
$contacts = $contact->find("firstname = 'John'"); // Finds all with firstname IS John
print_r($contacts); // Dump out the results on screen

$contacts = $contact->find("firstname like 'John%'"); // Finds all with firstname LIKE John%
print_r($contacts); // Dump out the results on screen

$contacts = $contact->find("firstname like 'John%'"); // Finds all with firstname LIKE John%
print_r($contacts); // Dump out the results on screen
</pre>
<p>Now once you have these record sets, you can easily loop through them and treat them individually like their own objects, and even update them. In my opinion, is much easier than writing a query, executing it, loading the results into a recordset and then accessing them. </p>
<pre name="code" class="php">
foreach($contacts as $singlecontact) {
	echo $singlecontact->firstname." ".$singlecontact->lastname."<br/>";
	$singlecontact->email = "email@address.com";
	$singlecontact->save();
}
</pre>
<p>These are all of the basic principals of the Active Record Implementation and the XML Data Dictionary Schema for ADOdb. There are a lot more things you can do with the Active Records, which I will hopefully dive into at a later date. The documentation on the <a href="http://adodb.sourceforge.net/">ADOdb Website</a> provides a LOT of examples that are practical to use, and they are what I used to learn the library myself and implement them in my day to day work.</p>
<h2>Further Reading</h2>
<p>For further reading, I would recommend the following links:</p>
<p><a href="http://adodb.sourceforge.net/">ADOdb @ SourceForge</a><br />
<a href="http://www.phpbuilder.com/columns/gilfillan20030617.php3">An introduction to the ADOdb class library for PHP</a><br />
<a href="http://phplens.com/phpeverywhere/?q=node/view/228">ADOdb Implementation of Active Record</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.greymass.com/adodbs-active-record-implementation-and-data-dictionary-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting started with ADOdb for PHP</title>
		<link>http://www.greymass.com/getting-started-with-adodb-for-php/</link>
		<comments>http://www.greymass.com/getting-started-with-adodb-for-php/#comments</comments>
		<pubDate>Fri, 01 May 2009 18:58:17 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[ADOdb]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.greymass.com/?p=144</guid>
		<description><![CDATA[<a href="http://adodb.sourceforge.net/">ADOdb</a> is a powerful database abstraction library for PHP (as well as <a href="http://phplens.com/lens/adodb/adodb-py-docs.htm">Python</a> designed to simplify some of the day to day database activities you may need in your PHP applications. I've used this library for about 3 years now, from site to site, just to simply the retrieval of data and cache the data locally for ease of use. ]]></description>
			<content:encoded><![CDATA[<p><a href="http://adodb.sourceforge.net/">ADOdb</a> is a powerful database abstraction library for PHP (as well as <a href="http://phplens.com/lens/adodb/adodb-py-docs.htm">Python</a>) designed to simplify some of the day to day database activities you may need in your PHP applications. I&#8217;ve used this library for about 3 years now, from site to site, just to simply the retrieval of data and cache the data locally for ease of use.</p>
<p><span id="more-144"></span><br />
Throughout this small guide, the focus will be on getting the most out of the ADOdb library for accessing <a href="http://www.mysql.com/">MySQL</a> databases. One of the best parts of ADOdb in my opinion is the ability to switch between different databases without having to change your code. The last application I created with the ADOdb library was written locally on my development machine using a <a href="http://en.wikipedia.org/wiki/LAMP_(software_bundle)">traditional LAMP</a> setup, but upon completion was deployed to a <a href="http://www.microsoft.com/windowsserver2008/en/us/default.aspx">Windows 2008</a> server running <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server">Microsoft&#8217;s SQL Server</a>. I encountered very few issues in the transition, as swapping between database types was really not an issue, as long as it was coded it properly.</p>
<p>Here&#8217;s a quick list of what exactly will be covered in this &#8220;getting started&#8221; post.</p>
<ul>
<h2>Contents</h2>
<li><a href="#part1">The Installation, Connection String and Config</a></li>
<li><a href="#part2">Performing a SELECT, looping through results</a></li>
<li><a href="#part3">Using the CACHE Mechanism to Speed up queries</a></li>
<li><a href="#part4">The EXECUTE Syntax for performing Updates/Inserts</a></li>
</ul>
<h2><a name="part1">The Installation, Connection String and Config</a></h2>
<p>First things first, you are going to need to include the ADOdb library in your website&#8217;s server someplace. The easiest way to do this, is simply to create a folder in your project, call it ADODB, and download the library into that folder.</p>
<p>You will find the Download for ADOdb here: <a href="http://sourceforge.net/project/showfiles.php?group_id=42718">http://sourceforge.net/project/showfiles.php?group_id=42718</a></p>
<p>There are 3 different versions, each suited to which version/language you will be using. Personally, I am using the PHP5 version of the library. Simply download the archive and extract it into your project in a folder of your choosing. For this example, lets put it into your document root into the ADODB folder. If you are feeling savvy, feel free to also create a location on your web server for the library, and simply modify your include paths to search that location.</p>
<p>Next you are going to need a database to play around with&#8230; I went ahead and created a database on my development machine called <strong>adodb_test</strong>, and created a table called <strong>contacts</strong> with the following SQL commands. This will also insert 2 example contacts into the table with dummy information.</p>
<pre class="php">CREATE DATABASE `adodb_test`;

CREATE TABLE `adodb_test`.`contact` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`FirstName` VARCHAR( 50 ) NOT NULL ,
`LastName` VARCHAR( 50 ) NOT NULL ,
`Phone` VARCHAR( 15 ) NOT NULL ,
`Email` VARCHAR( 100 ) NOT NULL
) ENGINE = MYISAM ;

INSERT INTO `adodb_test`.`contacts` (
`id` ,
`FirstName` ,
`LastName` ,
`Phone` ,
`Email`
)
VALUES (
NULL , 'Joe', 'User', '555-555-5555', 'joe@joeuser.com'
), (
NULL , 'John', 'Doe', '555-555-5555', 'john.doe@nobody.com');</pre>
<p>Now that you have the files downloaded and an example database setup, including it into your project is as simple as below.</p>
<pre class="php">$config['server'] = "localhost"; // The URL/IP for your database server
$config['dbtype'] = "mysql"; // The type of database we are using (mysql in this example)
$config['username'] = "username"; // Username to connect to the database
$config['password'] = "password"; // Password to connect to the database
$config['database'] = "adodb_test"; // The Name of the Database which to use

require_once("ADODB/adodb.inc.php");;
$db = NewADOConnection($config['dbtype']);
$db-&gt;debug = true;
$db-&gt;Connect($config['server'], $config['username'], $config['password'], $config['database']);

// Do your SQL work here

$db-&gt;close();</pre>
<p>Now generally I have a config.php file stored someplace out of my SVN repository, making it unique to each deployment of the application I create. The $config variables are usually set within this file, but for this example, I am trying to keep it all in a single script for ease of understanding.</p>
<p>The above code will establish a connection to your MySQL database or provide an error if it cannot. At the end, the $db-&gt;close() will terminate the database connection. The line of code &#8220;$db-&gt;debug = true&#8221; tells the library you are going to be in debug/development mode, and will output every single query that ADOdb executes, as well as provide errors on anything that might occur. It&#8217;s extremely useful for debugging your applications and seeing exactly what your code is trying to accomplish.</p>
<h2><a name="part2">Performing a SELECT, looping through results</a></h2>
<p>Well, now that we are connected, we might as well write a query for new table. Let&#8217;s say we want to write a command that will retrieve all of the contacts in our database. Well, there&#8217;s a nice little command that makes it easy to perform this action.</p>
<pre class="php">$res = $db-&gt;GetAll("select * from contacts");
foreach($res as $row) {
echo $row['FirstName']." ".$row['LastName']."
";
}</pre>
<p>This code will loop through every row returned from the database, echo&#8217;ing the first and last name of each person on its own line. You can also append a WHERE clause into this statement to refine your results. There are a few other nice commands that are useful when selecting records as well.</p>
<pre class="php">// Returns a single row, and single column based on WHERE criteria (or first available)
$res = $db-&gt;GetOne("select LastName from contacts WHERE FirstName = 'John'");
echo $res; // Returns "Doe"
// Returns an Array containing a single Row based on WHERE criteria (or first available)
$res = $db-&gt;GetRow("select * from contacts");
var_dump($res); // Returns the row for "John Doe"</pre>
<p>Pretty simple eh? This is one of the reasons I moved over to ADOdb a few years ago, was simply because I could write code more efficently that if I was just using straight PHP commands. Now that PHP has its <a href="http://us2.php.net/pdo">PDO Layer</a> its a lot easier to use with straight PHP, but I still prefer the ADOdb library, and hopefully through this article you will find out why.</p>
<h2><a name="part3">Using the CACHE Mechanism to Speed up queries</a></h2>
<p>A lot of applications repeat a lot of queries, over and over and over, and will return the same results during a period of time. Let&#8217;s say this example database of contacts is used for a user base of 10,000 users. Every time one of the users loads a page looking up an index of contacts, they will probably be getting the same results. In a normal application repeating and hammering our database server with all of these duplicate requests is counter productive, so what to do?</p>
<p>ADOdb provides a solution to your problem, it has built in record set caching, and its incredibly easy to use and build into your application. All of the above code does not use the cache system, but if you wanted it to, its as simple as changing the method you are calling from ADOdb.</p>
<pre class="php">$res = $db-&gt;CacheGetAll(60,"select * from contacts");
foreach($res as $row) {
echo $row['FirstName']." ".$row['LastName']."
";
}

// Returns a single row, and single column based on WHERE criteria (or first available)
$res = $db-&gt;CacheGetOne(60,"select LastName from contacts WHERE FirstName = 'John'");
echo $res; // Returns "Doe"
// Returns an Array containing a single Row based on WHERE criteria (or first available)
$res = $db-&gt;CacheGetRow(60,"select * from contacts");
var_dump($res); // Returns the row for "John Doe"</pre>
<p>Notice the change, all of the methods called from the ADOdb Object are now prefixed with the word <strong>Cache</strong>. Also notice, before the query, we now have a number being passed into the call. The number I chose for this example was 60, meaning that the query will be cached on the server&#8217;s disk for 60 seconds. If one user hits this page, and loads that query, it will record the results to a temp file on the server, and feed the results back for anyone else from the temp file for 60 seconds.</p>
<p>So what exactly does this do? Well, now lets say you do a query for all users with the last name starting with the letter &#8220;S&#8221;, and there are 5,000 results. That query is probably pretty intense if your database is that large. So now imagine if 3,000 people use that same query in a hour, it would be extremely intensive on your database, and might cause some problems with the server. So by using the ADOdb caching mechanism, you could set it up so that the first person that loads the page, actually hits the database, and then every user after that wouldn&#8217;t be using the database, but a flat file in your temp folder. The performance boost for applications like this would be incredible.</p>
<p>Now the caveat to this is, by using cached results you won&#8217;t be able to see immediate results, unless you design your update process to flush the cache whenever a record is updated. It&#8217;s the same theory that the <a href="http://ocaoimh.ie/wp-super-cache/?r=wpsc">WP Super Cache plug-in</a> for <a href="http://www.wordpress.com">WordPress</a> uses. Less Database Calls, more Flat Files, but the same functionality as a dynamic application.</p>
<h2><a name="part4">The EXECUTE Syntax for performing Updates/Inserts</a></h2>
<p>Updating and Inserting is pretty much just as easy as running queries against the database, very straight forward in how you can use the execute statement.</p>
<pre class="php">$db-&gt;Execute("INSERT INTO contacts VALUES (null,'Firstname','Lastname','phone','emailaddress')");

// or
$sql = "INSERT INTO contacts VALUES (null,'Firstname','Lastname','phone','emailaddress')";
$db-&gt;Execute($sql);</pre>
<p>Essentially all the execute command is doing is running whatever SQL you are putting into the EXECUTE command, and will return either true or false based on whether it succeeds or not. You can use the EXECUTE command to fire stored procedures or any SQL command that you would like just to pass straight to the database.</p>
<h2>More about ADOdb to Come!</h2>
<p>In the next post about ADOdb I am going to cover using the ADOdb Active Records implementation as well as using XML to generate and update your table schema. There are some downfalls to using ADOdb&#8217;s Active Record implementation, but let me tell you, they are incredibly organized and a great tool for developing complex applications.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.greymass.com/getting-started-with-adodb-for-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using cURL to Grab Data</title>
		<link>http://www.greymass.com/using-curl-to-gather-data/</link>
		<comments>http://www.greymass.com/using-curl-to-gather-data/#comments</comments>
		<pubDate>Fri, 24 Apr 2009 16:27:07 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[curl]]></category>
		<category><![CDATA[phpinfo]]></category>
		<category><![CDATA[scrape]]></category>

		<guid isPermaLink="false">http://jesta.us/?p=31</guid>
		<description><![CDATA[Using cURL is a simple and effective way to gather data from another website, run it through a script, parse the data and transform it into something useful that you can use on your website. Whether you are &#8220;scraping&#8221; data to build a summary of a link, pulling an XML file to parse into a [...]]]></description>
			<content:encoded><![CDATA[<p>Using cURL is a simple and effective way to gather data from another website, run it through a script, parse the data and transform it into something useful that you can use on your website. Whether you are &#8220;scraping&#8221; data to build a summary of a link, pulling an XML file to parse into a database, or just simply wanting to get the contents of the file, cURL is a simple and effective way to pull the data from an outside source into your page.</p>
<p><span id="more-31"></span><strong>Making sure cURL is enabled and setup</strong><br />
First things first, you need to make sure cURL is enabled on your web host. The easiest way to accomplish this is to check your phpinfo on your server. Simply deploy a PHP file with the following information onto your server, and name it whatever you want.</p>
<pre name="code" class="php">
&lt;?
phpinfo();
?&gt;
</pre>
<p>After the file is uploaded/saved onto your web server, look through the file to ensure that there is a section that looks as follows.</p>
<p><a href="http://www.greymass.com/wp-content/uploads/2009/04/phpinfo_curl.png"><img src="http://www.greymass.com/wp-content/uploads/2009/04/phpinfo_curl.png" alt="phpinfo_curl" title="phpinfo_curl" width="498" height="91" class="aligncenter size-full wp-image-109" /></a></p>
<p>If your PHP file doesn&#8217;t have this section of code, or nothing similar to it, then your hosting service may not support cURL, or it may not be enabled. If you are on a hosting service, you can ask your host to enable it for you, or if you are on your own server, you can modify your php.ini file to enable the extension. </p>
<p>You can modify your php.ini file as follows:<br />
(if you can&#8217;t find it, look at the top of the script we wrote above, it will give you the ini path)</p>
<pre name="code" class="php">
// Find this line in your php.ini
;extension=php_curl.dll

// Remove the semi-colon in front, to make the line look like this:
extension=php_curl.dll
</pre>
<p>After modifying and saving your php.ini file, you are going to have to restart your web service. </p>
<p>- If you are running on Apache, you should be able to enable it with a simple &#8220;apachectl restart&#8221; command. </p>
<p>- If you are running an IIS web server, you are going to have to restart IIS or just restart the Worker Pool that is running your PHP. This can be done through the MMC IIS Snap-In. </p>
<p>- If you are running WAMP on your local machine, simply right-click on the WAMP icon in your system tray, find the Apache menu, and click &#8220;Restart&#8221;.</p>
<p>Just make sure you go back into your file running phpinfo() to ensure that cURL is showing up in the file now. If not, you may want to seek addition support from your IT, Co-workers or Web hosting provider for more information as to why cURL will not function on your server. </p>
<p>Assuming everything is running now, and cURL is enabled, we will continue onwards. </p>
<p><strong>A simple cURL Request</strong></p>
<p>cURL isn&#8217;t incredibly hard to use to pull the data in, as illustrated below.</p>
<pre name="code" class="php">
&lt;?php
// Init $curl as a cURL object
$curl = curl_init();

// Tell cURL what URL we are going after
curl_setopt($curl, CURLOPT_URL, 'http://www.google.com');

// Tell cURL we would like headers as well
curl_setopt($curl, CURLOPT_HEADER, 1);

// Tell cURL we would like the results as a string instead of just dumping it on the screen
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

// Execute the cURL request
$data = curl_exec($curl);

// Close the cURL request
curl_close($curl);

// Display the data from the variable to ensure its there.
var_dump($data);
</pre>
<p>The above set of code will go out to http://www.google.com and will set the variable $data to contain the HTML contents of the website. The var_dump($data) at the end of the file merely spits it back out onto your screen so you can see the data you have to work with. </p>
<p>Now, what you end up doing with this data is up to you! You could run it through some regex statements to pull relevant information, you could parse it line by line and store certain portions of code somewhere, or if you are pulling an XML file, you could begin to parse the XML. Since this article is just about cURL, we won&#8217;t get into that.</p>
<p><strong>Using a cURL Request Object</strong></p>
<p>A bit more on the advanced side, but if you want to create a function to handle all your requests for you, I&#8217;ve pulled one out of my code library that you may find useful. </p>
<p>(Thanks to <a href="http://www.dzone.com/links/users/profile/233461.html">antych</a> for the tip at <a href="http://www.dzone.com/links/using_php_and_curl_to_grab_data.html">dzone.com</a>)</p>
<pre name="code" class="php">
&lt;?php
function curlURL($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2');
    $output = curl_exec($curl);
		return $output;
}

$curlResults = curlURL("http://www.google.com");

// Display what we've found
var_dump($curlResults);
</pre>
<p>Well, gathering data this way is pretty simple when you know what you are passing in. Notice above in my firefox, that I am passing a Firefox browser string into the cURL request. Why is this? Well some websites try to block cURL or automated requests (such as the World of Warcraft Armory, which is what I was scraping), so by mimicking a browser, we can get past these obstacles. </p>
<p>Now what you do with all of this new found data, well that is up to you. Eventually I will create a post more about parsing this data you find, but that is for another day.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.greymass.com/using-curl-to-gather-data/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>PHP Basics &#8211; Syntax for Dummies</title>
		<link>http://www.greymass.com/php-basics-syntax-for-dummies/</link>
		<comments>http://www.greymass.com/php-basics-syntax-for-dummies/#comments</comments>
		<pubDate>Thu, 23 Apr 2009 19:58:36 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[functionality]]></category>
		<category><![CDATA[simple logic]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://jesta.us/?p=25</guid>
		<description><![CDATA[There is a lot of PHP specific syntax that every PHP programmer uses in their day to day work, that everyone has just learned that it is the way it is meant to be. But, to truly be able to go through, read someone&#8217;s code and truly understand it, you need to know exactly what [...]]]></description>
			<content:encoded><![CDATA[<p>There is a lot of PHP specific syntax that every PHP programmer uses in their day to day work, that everyone has just learned that it is the way it is meant to be. But, to truly be able to go through, read someone&#8217;s code and truly understand it,  you need to know exactly what the syntax means, and why it&#8217;s formatted that way. Throughout this small post, there are just some thoughts and practices for coding using the PHP syntax.</p>
<p><span id="more-25"></span><br />
<strong>The Semicolon</strong></p>
<p>The basic syntax of PHP, which is the first thing every PHP developer needs to know, is the semicolon. Most lines of code end with a semicolon, which essentially means, to execute the code that has been loaded before this semicolon and after the last one.</p>
<pre class="php">$foo = "bar";
$fooArray = "Bar",
            "This",
            "Something";</pre>
<p>You can break your code into multiple lines in some cases, but technically the code above is still only two lines of code. The first line of code assigns the variable of $foo, and the second line sets an array called $fooArray. Even though the array is broken into three separate lines, it still executes as one line of code.</p>
<p>Notice how still, each line of code ends with a semicolon. You cannot split every line up like this, but when assigning arrays, building long strings, or even working with objects, you can drop down and create a new line. The reasoning behind this will be covered more in the &#8220;Making your code Pretty&#8221; article.</p>
<p><strong>The period as a &#8220;String Connector&#8221;</strong></p>
<p>Some languages use the plus symbol (+), some languages use variations of quotes, and PHP uses the period (.) as a string connector.</p>
<pre class="php">// --- Long Method
echo "Your IP address is: ";
echo $_SERVER['REMOTE_ADDR'];
echo " &lt;br/&gt;";
echo "The current date/time is: ";
echo date("Y-m-d H:i:s");
echo " &lt;br/&gt;";

// --- Short Method
echo "Your IP address is: ".$_SERVER['REMOTE_ADDR']." &lt;br/&gt;";
echo "The current date/time is: ".date("Y-m-d H:i:s")." &lt;br/&gt;";</pre>
<p>The two above examples will yield the exact same results, example #1 not using any string connectors, example #2 joining strings using the period. You can use this syntax to set variables, within functions, or nested inside of loops. Essentially what you are doing is appending to the current string with what is after the period. By joining multiple strings together with the &#8220;something&#8221;.$something.&#8221;something&#8221; method, you can easily assemble long strings without having to write an incredible amount of code.</p>
<p><strong>(Encapsulating with Parenthesis)</strong></p>
<p>This is just like algebra folks&#8230; things within parenthesis will be evaluated before the rest of the equation.</p>
<pre class="php"> 	echo 1 + 6 * (( 8 - 5 ) / 2 );

	// Order of Operations:
	// 8 - 5 = 3
	// 3 / 2 = 1.5
	// 6 * 1.5 = 9
	// 1 + 9 = 10
	// echo 10</pre>
<p>The comment above shows the order of operations, which is identical to that of an algebra equation. Evaluate the values inside the parenthesis first, work your way outwards, then use the standard order.</p>
<blockquote><p><strong>Order of Operations</strong><br />
Source: <a href="http://www.math.com/school/subject2/lessons/S2U1L2GL.html">http://www.math.com/school/subject2/lessons/S2U1L2GL.html</a></p>
<p>1. First do all operations that lie inside parentheses.<br />
2. Next, do any work with exponents or radicals.<br />
3. Working from left to right, do all multiplication and division.<br />
4. Finally, working from left to right, do all addition and subtraction.</p></blockquote>
<p><strong>Brackets and Uses</strong></p>
<p>Brackets, as in [], are primarily used for assigning or calling values from an array.</p>
<pre class="php">	// Example #1
	$array = array("red","green","blue");
	echo $array[0]; // Will display "red"
	echo $array[1]; // Will display "green"
	echo $array[2]; // Will display "blue"

	// Example #2
	$array = array("color1"=&gt;"red");
	echo $array['color1'];</pre>
<p>By default an array will populate its keys with numbers, in the above example, it does just that. When passing values into an array, each value is assigned an auto-incremented number, starting at zero. To reference these values in an array in the most simple fashion, you simply put the key you wish to call on within brackets.</p>
<p>These keys do not have to be numbers, they can be strings as well, and the values of the array can be pretty much any type of variable or object. The second example shows that you can pass in a string within the brackets to pull out the value for that specified key.</p>
<p>For more information on arrays, please see: <a href="http://www.greymass.com/php-basics-the-array/">PHP Basics &#8211; The Array</a>.</p>
<p><strong>What are those &#8220;Curly Brackets&#8221; used for?</strong></p>
<p>The { and }? They are actually called &#8220;Braces&#8221; and are used to define the starting and ending of a structure of code. The most common use of them while starting is to start a loop or if-statement. The &#8220;Open Brace&#8221; or {, signifies we are starting an structure of code that will continue until the &#8220;Close Brace&#8221;, or }. This is easily seen in an if-statement as seem below.</p>
<pre class="php">if($foo == "bar") { // This brace starts the structure
	// Do something!
} // This brace ends it</pre>
<p>The code encased in the braces will only execute if the condition of the if-statement evaluates to TRUE. There are also other methods of starting and stopping an if-statement or loop, but we will wait to get into those later, as to not confuse people.</p>
<p>Braces are also used to define function, class and namespace contents. These are a little further along, but still solid examples.</p>
<pre class="php">	function doWork($foo) {
		// Perform Actions on $foo
		return $bar;
	}

	class foo extends bar {
		private $var = "test";

		public function doWork($var) {
			// Do Work!
			$this-&gt;var = $mod;
		}
	}</pre>
<p>Notice in the second example, there are nested braces within. Each brace has a start and a stop, telling the system which pieces belong in which places. When your code starts getting extremely messy or complex, its always a good idea to keep the braces lined up with the same spacing for ease of reading. Yet another topic for another day.</p>
<p><strong>The Key=&gt;Value Syntax</strong></p>
<p>The last syntax covered in this post is the $key=&gt;$value assignment syntax, which can be a little confusing at first. This is primarily used in arrays and is meant to set specific keys to specific values.</p>
<pre class="php">  $key = "key";
  $value = "value";

	$array = array($key=&gt;$value);
	$array = array("key"=&gt;"value");

	echo $</pre>
<p>The two above examples will both assign the $array variable to contain the same array; a single key named &#8220;key&#8221; will be assigned the value of &#8220;value&#8221;. The =&gt; syntax states that you are using a key=&gt;value combo to pull this off. This can also be used in a foreach() loop to iterate through an array of values, as seen below.</p>
<pre class="php">$array = array("color1"=&gt;"red", "color2"=&gt;"blue");

foreach($array as $key=&gt;$value) {
	echo $key." = ".$value."&lt;br/&gt;";
}

// Outputs:
// color1 = red
// color2 = blue</pre>
<p>The loop will go through every item in the $array variable, and display every key=&gt;value combo within it.</p>
<p>Well, that&#8217;s it for the basics of syntax. Stick around for more info at another time!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.greymass.com/php-basics-syntax-for-dummies/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PHP Basics &#8211; The Operators (Part 2)</title>
		<link>http://www.greymass.com/php-basics-the-operators-part-2/</link>
		<comments>http://www.greymass.com/php-basics-the-operators-part-2/#comments</comments>
		<pubDate>Tue, 21 Apr 2009 18:59:20 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[algebra]]></category>
		<category><![CDATA[comparison operators]]></category>
		<category><![CDATA[Operators]]></category>
		<category><![CDATA[simple logic]]></category>

		<guid isPermaLink="false">http://jesta.us/?p=72</guid>
		<description><![CDATA[In our first section, we talked about the multiple ways that you can use the equals sign to assign variables or compare them, based on value and type. In part 2 of this series, we are going to dive deeper into the comparison operators, and exactly how they function. There is a lot of basic [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.greymass.com/php-basics-the-operators-part-1/">our first section</a>, we talked about the multiple ways that you can use the equals sign to assign variables or compare them, based on value and type. In part 2 of this series, we are going to dive deeper into the comparison operators, and exactly how they function. There is a lot of basic programming concepts here, but where better to start than the basics.</p>
<p><span id="more-72"></span><br />
Starting off, we will look at the greater than and less than operators, which are going to be extremely simple and to the point.</p>
<pre name="code" class="php">
$a = 1;
$b = 2;

$result = $a > $b;
echo "a > b = ";
echo $result;
echo "<br/>";
$result = $a < $b;
echo "a < b = ";
echo $result;
</pre>
<p>The above lines of code will output that "a > b = false" (false doesn't echo), and "a < b = true". What does this mean? It means that the values returned by greater than and less than statements are either true or false. The above would be an extremely strange way of finding your results, so I am going to use a more common example next.</p>
<pre name="code" class="php">
 if($a > $b) {
   echo "a is greater than b";
 } else {
   echo "a is less than b";
 }
</pre>
<p>Essentially what you are saying, is IF <strong>A</strong> is greater than <strong>B</strong>, then display the echo, else move on down to the bottom portion. Pretty simple, so moving on, here are two new operators.</p>
<pre name="code" class="php">
 if($a >= $b) { }
 if($a <= $b) { }
</pre>
<p>It's just what it looks like, greater than <strong>OR</strong> equal to. Now your mixing and matching operators, stating maybe that you want something above/equal to, or less than/equal to. It's extremely simple logic/algebra here, just to check the values of these variables.</p>
<p>Onto a little something more complicated, the <strong>not</strong> operator.</p>
<pre name="code" class="php">
 $a = 1;
 $b = 2;
 if($a != $b) { echo "not equal"; }
</pre>
<p>The exclamation point in front of the equals means we are making sure they are <strong>not</strong> the same value. This is extremely useful when you are building something that cannot have identical values. The "!=" statement checks the two variables to make sure they are not equal to each other, but does not care whether or not they are the same data type. Get where this is going from the "triple equals" from the first article?</p>
<pre name="code" class="php">
 $a = 1;
 $b = "1";
 if($a !== $b) { echo "not equal or not the same type"; }
</pre>
<p>By using the single exclamation and the double equals, it is now also checking the variable types to make sure they are not the same. Even though technically both of the variables are equal to 1, $b is a string, and $a is an integer, so this statement will return and tell you they are "not equal or not the same type".</p>
<p>Well, these are all the basic operators. The next set of operators won't come up until the more advanced articles, where we will talk about Ternary Operators.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.greymass.com/php-basics-the-operators-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Basics &#8211; The Array</title>
		<link>http://www.greymass.com/php-basics-the-array/</link>
		<comments>http://www.greymass.com/php-basics-the-array/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 21:16:17 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[variable types]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://jesta.us/?p=60</guid>
		<description><![CDATA[One of the fundamental variable types, yet one of the more complex when you are beginning, is the Array. The array just takes a little bit to wrap your mind around, or maybe a good analogy as to exactly what it is doing. You can pretty much think of an array as a mini-storage unit [...]]]></description>
			<content:encoded><![CDATA[<p>One of the fundamental variable types, yet one of the more complex when you are beginning, is the <strong>Array</strong>. The array just takes a little bit to wrap your mind around, or maybe a good analogy as to exactly what it is doing.</p>
<p>You can pretty much think of an array as a mini-storage unit for variables, someplace to order them, keep them in one space, and reference them by name dynamically. There are more advanced ways to do some of this as well but arrays are a good starting point.</p>
<p><span id="more-60"></span><br />
Just as a starter, here is a basic array, the first code snippet is the PHP to write the array, and the second is a visual representation of the variable.</p>
<pre name="code" class="php"> $variable = array("red","green","blue");</pre>
<pre name="code" class="php">$variable = Array
(
    [0] =&gt; red
    [1] =&gt; green
    [2] =&gt; blue
)</pre>
<p>Now, a brief overview at exactly what you are looking at here, in case you have never worked in an array before. The variable named $variable is an array, and it contains 3 values, &#8220;Red&#8221;, &#8220;Green&#8221; and &#8220;Blue&#8221;. Each of these values now has dynamically been assigned a number on the left hand column. These are the <strong>keys</strong> to access the data in the array.</p>
<p>If you were to make an analogy to understand it better, we could say an array is a book, and each variable in the array is a page. Each page has a page number, and those page numbers would be the keys in the array. Let&#8217;s run with that example, and create a bit more complex of an array, so and pretend our array is indeed a book.</p>
<pre name="code" class="php"> $book = array(
     "The quick brown dog...",
     "Jumped over the big red fence...",
     "To get to his food..."
  );</pre>
<p>Don&#8217;t let the change of how I typed the code throw you off, this is the exact same sample as above, instead we have a &#8220;page&#8221; of the &#8220;book&#8221; stored within each &#8220;page number&#8221;. Notice how the variable looks now:</p>
<pre name="code" class="php">Array
(
    [0] =&gt; The quick brown dog...
    [1] =&gt; Jumped over the big red fence...
    [2] =&gt; To get to his food...
)</pre>
<p>The variable is still pretty much the same, just with different values stored within its keys. So now, if we were going to print out the first value of the array to the screen, we would echo it out, with slightly different syntax than just a standard echo.</p>
<pre name="code" class="php"> echo $book[0];</pre>
<p>You would echo it just like a standard variable, except directly after,  you would use brackets to specify which key you want to retrieve from the array. The above code would output &#8220;The quick brown dog&#8230;&#8221; onto the screen. You can simply change the number at the end of the variable to specify which portion of the array you are looking for.</p>
<p>The above syntax you can also set values in an array with as well!</p>
<pre name="code" class="php"> $book[4] = "This is another page!";
 $book[1000] = "This is WAY out there...";</pre>
<p>These two lines of code will write their values into the key of 4 and key of 1000. There&#8217;s nothing telling you that you have to use numbers in order, or even numbers for that example!</p>
<pre name="code" class="php"> $book['index'] = "This is the index of the book";</pre>
<p>You can store keys with words as well, if that helps you organize how your data is stored. PHP uses a lot of arrays for sessions, server variables and many other things. Here&#8217;s an example of pulling the IP address of your client, from a $_SERVER variable that is automagically set whenever a script on your server is called.</p>
<pre name="code" class="php"> echo $_SERVER['REMOTE_ADDR']; // Will print the IP address accessing the script</pre>
<p>Arrays can be an amazing storage tool to keep your variables in check, instead of assigning every single variable its own name. It also is nice if you want to pass multiple variables into a function or an object&#8217;s method at once. That&#8217;s a little bit more advanced, and a subject for another time, but just understanding the basics of how an array looks, visually and in concept, will take you a long ways.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.greymass.com/php-basics-the-array/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP Basics &#8211; The Operators (Part 1)</title>
		<link>http://www.greymass.com/php-basics-the-operators-part-1/</link>
		<comments>http://www.greymass.com/php-basics-the-operators-part-1/#comments</comments>
		<pubDate>Fri, 17 Apr 2009 17:09:48 +0000</pubDate>
		<dc:creator>Aaron</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Expression]]></category>
		<category><![CDATA[Operators]]></category>

		<guid isPermaLink="false">http://jesta.us/?p=20</guid>
		<description><![CDATA[Coming into PHP fresh, you may notice a few things that don&#8217;t exactly line up with some of the other programming languages out there. In this initial &#8220;Operators&#8221; post, I am going to talk a little bit about the different operators that are available for people programming in PHP. There are different ways to compare [...]]]></description>
			<content:encoded><![CDATA[<p>Coming into PHP fresh, you may notice a few things that don&#8217;t exactly line up with some of the other programming languages out there. In this initial &#8220;Operators&#8221; post, I am going to talk a little bit about the different operators that are available for people programming in PHP. There are different ways to compare and assign variables, as well as the reasons you might want to use each of these. It&#8217;s a good springboard or starting point for starting to understand PHP.</p>
<p><span id="more-20"></span><br />
<strong>The Equals (=) Operator</strong></p>
<p>The primary role of the equals operator I would consider is setting variables. The single equals role is to set the variable on the left, to the value on the right.</p>
<pre name="code" class="php">$foo = "bar";</pre>
<p>This will set the variable named $foo to contain a string value of &#8220;bar&#8221;. Simple eh?</p>
<p>Well, now what happens if you double up your equals?</p>
<pre name="code" class="php">$foo == "bar";</pre>
<p>It no longer will set the variable $foo equal to &#8220;bar&#8221;, instead what it is doing is comparing the variable on the left to the value on the right. So really, the above line of code is totally impractical, because really it isn&#8217;t doing anything. Lets write something that makes a little bit more sense.</p>
<pre name="code" class="php">if($foo == "bar") {
  echo $foo;
}
</pre>
<p>So the &#8220;IF Statement&#8221; above now is a better idea of exactly what is going on here. The statement is saying:</p>
<blockquote><p>&#8220;IF <strong>$foo</strong> is set to &#8216;bar&#8217;, lets display the value of <strong>$foo</strong> on the page.&#8221;</p></blockquote>
<p>The Double Equals expression doesn&#8217;t care what type of variable $foo is, as its moving through, which leads to the next point. The Triple Equals operator. This ones a little bit trickier and is very, very specific. In the following example, we are no longer going to use a string for the value of $foo, but instead use a number as a string and as an integer.</p>
<pre name="code" class="php">
Example 1:
$foo = 1;

if($foo === 1) {
  echo $foo;
}

Example 2:
$foo = "1";

if($foo === 1) {
  echo $foo;
}
</pre>
<p>Example #1 will display the value of $foo, while Example #2 will not.</p>
<p>The two above samples are almost identical, except for the fact that the value of $foo in Example #2 is encased in quotes, telling it that the variable is a string instead of an integer. The Triple Equals Operator not only compares the values of the variable, but it also compares the <strong>type</strong> of variable being passed in. This is extremely useful when you have code that will only function against a specific type of variable.</p>
<p>One last thing, and this is veering off topic a little bit, but you can cast the variables in the above statement if your really want to use quotes.</p>
<pre name="code" class="php">
$foo = (int) "1";

if($foo === 1) {
  echo $foo;
}
</pre>
<p>By placing the <strong>(int)</strong> in front of the value you are setting, you are casting that variable as a specific type. It&#8217;s useful when you want to specifically set a variable as well, but you might have some problems between variable type conversions if you&#8217;re always casting every variable.</p>
<p>But that&#8217;s a topic for another day, another post. Perhaps the next operator post, we will do some &#8220;not&#8221; functionality.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.greymass.com/php-basics-the-operators-part-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

