<?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>Webmonkey &#187; MySQL</title>
    <atom:link href="http://www.webmonkey.com/tag/mysql/feed/" rel="self" type="application/rss+xml" />
    <link>http://www.webmonkey.com</link>
    <description>The Web Developer&#039;s Resource</description>
    <lastBuildDate>Fri, 05 Apr 2013 20:20:46 +0000</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <generator>http://wordpress.org/?v=3.4.2</generator>
    
    <item>
        <title>Build a Website With Flash and MySQL &#8211; Lesson 1</title>
        <link>http://www.webmonkey.com/2010/02/build_a_website_with_flash_and_mysql_-_lesson_1/</link>
        <comments>http://www.webmonkey.com/2010/02/build_a_website_with_flash_and_mysql_-_lesson_1/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=682</guid>
        		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Multimedia]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[Overview There&#8217;s always been somewhat of a disconnect between designer-types and backend-types. And we&#8217;re not just talking about hairstyles, eyewear, and the contents of their bookshelves &#8212; designers and programmers approach problems in different ways, and their individual plans of attack don&#8217;t always jibe. Of course, you want your site to be sleek, fast, and [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><b>Overview</b>

</p><p>There&#8217;s always been somewhat of a disconnect between designer-types and backend-types. And we&#8217;re not just talking about hairstyles, eyewear, and the contents of their bookshelves &#8212; designers and programmers approach problems in different ways, and their individual plans of attack don&#8217;t always jibe. Of course, you want your site to be sleek, fast, and bleeding-edge, but are you willing to compromise stability, scalability, and compatibility just so the users can ooh and aah at a few pretty pictures? Web design has always been a balancing act, and the ideologies of each camp often clash.

</p><p>But Webmonkey&#8217;s here to say that it doesn&#8217;t have to be that way. It is possible to create a site that has a lightweight Flash frontend, a dreamy interface, and a scalable, secure, and dynamic backend.

</p><p>Webmonkey Scott has found the balance between eye-catching design and backend database wizardry. Lucky for us, he&#8217;s agreed to share this knowledge in a two-day tutorial. He&#8217;s even put together a hands-on project that shows you how to build an easy-to-update blog using Flash. That&#8217;s right, a Flash-based blog &#8212; it sounds a little loony, but this blog pulls content from a MySQL database and feeds it into the dynamic Flash frontend using a few lines of PHP code.

</p><p>In day one, Scott talks you through the construction of an open source MySQL database using both the phpMyAdmin tool and mysql on the command line. You&#8217;ll learn how to add blog entries to the database and then you&#8217;ll learn how to run queries in PHP. Topics such as basic database organization and the behavior of variables are also covered in this lesson.

</p><p>Day two shows you how to design and build the blog&#8217;s Flash frontend. You&#8217;ll use common Flash ActionScript objects to pull the content from your MySQL database to the different areas of your blog&#8217;s user interface. You&#8217;ll also learn some common workarounds to keep all of your content flowing smoothly.

</p><p>Whether you are designer or a programmer, it&#8217;s time to roll up those sleeves and get ready to see how the other half lives. Even if those of you who don&#8217;t feel a particular loyalty to either side of the fence will still discover that there&#8217;s plenty of hands-on knowledge to be gained.

</p><p>We&#8217;re not promising that designers will sell their $500 pencil sharpeners, start marrying UNIX geeks, and honeymooning in Cancun before breeding programmer/designer children, but we will insist that they sit in a room alone together until they can build a useful website that everyone can agree on. Hey, stranger things have happened. Like <a href="http://www.mcsweeneys.net/links/lists/carrottop.html" class="external text" title="http://www.mcsweeneys.net/links/lists/carrottop.html" rel="nofollow">Carrot Top</a>.



</p><span id="more-682"></span><p><br />

</p>

<table id="toc" class="toc" summary="Contents"><tbody><tr><td><div id="toctitle"><h2>Contents</h2> </div>

<ol>

<li><a href="#Building_with_Flash_and_MySQL">Building with Flash and MySQL</a></li>

<li><a href="#PHP_Basics">PHP Basics</a></li>



<li><a href="#Using_MySQL">Using MySQL</a></li>

<li><a href="#Creating_the_Database">Creating the Database</a></li>

<li><a href="#Entering_Data">Entering Data</a></li>

<li><a href="#Add_a_Dash_of_PHP">Add a Dash of PHP</a></li>

<li><a href="#Strings.2C_Sealing_Wax.2C_Fancy_Stuff">Strings, Sealing Wax, Fancy Stuff</a></li>







</ol>

</td></tr></tbody></table>



<a name="Building_with_Flash_and_MySQL"></a><h4> <span class="mw-headline">Building with Flash and MySQL</span></h4>

<p>From the beginning, the database has been the sole province of programming geeks. For designers, usually geeks themselves, but with backgrounds in color theory or animation rather than code architecture, the jargon surrounding databases is often confusing, overwhelming, and intimidating. Even so, the irony is that designers are sometimes the very people who can benefit the most from using a database.

</p><p>Many designers can create eye-popping sites full of life, but it&#8217;s rare to find a designer who can sustain that initial vibrancy as the site ages. How often have you seen an amazing-looking site that was created, hyped, then abandoned?

</p><p>Database integration can propel a website from a well-designed but infrequently updated bore to a dynamically generated, updated-on-the-fly extravaganza for the mind. Connecting your design to content driven by a database gives you or your clients a site that can be updated easily without ever needing to touch the design elements themselves. Also, this separation of content and container will make your job as a designer much easier. With the continuous flow of timely content from your easy-to-update database, your site will stay fresh and youthful. It works better than any of those creams from France, anyway.

</p><p>As a good designer, you&#8217;re capable of translating loosely held, often ill-conceived ideas into the sites we all use and enjoy. What&#8217;s more you make them look <i>good</i>. But perhaps dealing with raw code is not your forte. Not to worry, it&#8217;s not as difficult as you might think.

</p><p>To get the full benefits a database offers, we&#8217;re going to feed our content into a Flash movie rather than an HTML page. Why would you want to do that, you ask? As a seasoned Web surfer, you&#8217;re probably familiar with the so-called &#8220;blink&#8221; of HTML. The process goes a little something like this:You click a link, the link then sends a command (often via PHP, which we&#8217;ll use here) to a database to retrieve whatever information you&#8217;re after. Once the database has retrieved your information, it sends that info back to the page that requested it. Now, if that page is HTML, your browser must weed through the results and shape them accordingly. But, before it can do any of that, the browser must first empty out the old page and create that momentary blank browser window &#8211; the blink of HTML.

</p><p>This doesn&#8217;t happen with Flash. Flash can load the data into the very same place from which it was requested without a visible refresh. No blink. No redrawing of elements that haven&#8217;t changed. In short, a smoother, less distracting transition for your user which leads to a better, more enjoyable viewing experience.

</p><p>Everybody convinced? Then let&#8217;s get started.

</p>

<a name="PHP_Basics"></a><h4> <span class="mw-headline">PHP Basics</span></h4>



<p>If you&#8217;ve worked with databases before, even if you&#8217;ve always fed the content into HTML pages, you&#8217;ll have a head start here. I&#8217;ll be assuming that you have MySQL and PHP installed and running on your server. If you&#8217;re going to be doing this through your Web hosting company, check to see if they already have the necessary software installed. If you find that you need to install either program, check out <a href="/2010/02/PHP_and_MySQL_Tutorial" title="Tutorial:PHP and MySQL Tutorial"> PHP and MySQL Tutorial</a>, which will also be a helpful read for those of you who&#8217;ve never worked with PHP since it goes into a little more detail on the syntax. The <a href="http://www.mysql.com" class="external text" title="http://www.mysql.com" rel="nofollow">homebase for MySQL</a> has a full manual available for download, as does the <a href="http://www.php.net" class="external text" title="http://www.php.net" rel="nofollow">official PHP site</a>. Take advantage of these free resources. Many hardworking volunteers have created them for you, and answers to most nitty-gritty questions can be found on one of those sites.

</p><p>If your website is hosted by someone other than yourself, you will have to ask your hosting company how to connect and interact with your database. Most good hosting companies will have you interact with your database via your Web browser and the <a href="http://www.phpmyadmin.net/home_page/" class="external text" title="http://www.phpmyadmin.net/home_page/" rel="nofollow">phpMyAdmin</a> program. The application will give you a nice graphical interface for creating tables and entering information. Also, phpMyAdmin shows you the actual MySQL syntax for your actions, which will let you get a better feel for how MySQL works. Really good hosting companies will let you connect directly via a secure shell or some other graphical program of your choice.

</p><p>There are many other graphical ways to interact with MySQL, but for the purpose of this tutorial, I will be giving examples from a terminal interface using the mysql client program, which comes with the MySQL package.

</p><p>Why use a terminal when GUIs of all shapes and sizes are available? Graphical interfaces may allow you to interact and manipulate data, but they often do so without letting you understand exactly what it is you&#8217;re doing. Typing the commands in a terminal session will help you not only learn the SQL syntax but understand how and why you&#8217;re doing what you&#8217;re doing. Knowledge of the SQL syntax will give you a better understanding of how to use PHP to manipulate SQL data. And what are you going to do when you land that dream project you spent months pitching only to learn you aren&#8217;t going to have access to a GUI? Over-reliance on GUIs is not the monkey way. Don&#8217;t let the command line intimidate you.

</p><p>To take full advantage of the organization a database offers, it helps to sit down ahead of time with a pen and piece of paper (made from trees &#8230; or even better, recycled material &#8230; like in high school) and plan out your database. Databases are simply means of organizing information into tables. Tables are made up of columns and rows. Typically each vertical column is some category of information and each horizontal row is an individual instance of that information. Too abstract? Think of your monthly bank statement. If it&#8217;s anything like mine, it&#8217;s a simple table (full of zeros). Across the top are column definitions (check number, payee, amount, et cetera). Reading horizontally, each line contains values that are given meaning by the column they&#8217;re in. MySQL databases work very much the same way. We create tables, define columns, and enter rows of data. The main difference is that our information will be searchable by any criteria we define.

</p><p>Unfortunately, those MySQL searches cannot be run directly from your browser. Thus, while we can enter the commands and search in our terminal (or GUI bad monkey, no banana), we can&#8217;t write some HTML code and duplicate those search results. But that&#8217;s OK, because there are other languages that <i>can</i> duplicate them. The two main languages used in a database search, or <i>query</i>, are PHP and Perl. For our purposes, which will be to deliver Web content to Flash, we&#8217;re going to use PHP. PHP was developed to specialize in database connections on the Web.



</p><p>Chances are many of the sites you visit everyday are generated using PHP. You&#8217;ve been seeing the benefits without ever knowing what was going on behind the nicely formatted information you receive. How did PHP give you your information without you even knowing it was doing so? If you view the source of a PHP page you will only see HTML. Where the <i>heck</i> is the PHP and how does it do what it does? We&#8217;ll get to that part a little later. Right now let&#8217;s dive into MySQL and feed it some information.

</p>

<a name="Using_MySQL"></a><h4> <span class="mw-headline">Using MySQL</span></h4>

<p>Databases are serious stuff my friends, and databases call for serious examples. When I think of seriousness and integrity on the Web, the first thing that comes to mind is the weblog. Ahem.

</p><p>Anyway let&#8217;s suppose you&#8217;re one of the two people who don&#8217;t yet have a blog. Or even better, let&#8217;s suppose you want to create a weblog that&#8217;s a little different from the endlessly repeated templates you see everyday. Let&#8217;s suppose for a moment that you want to create your very own <i>Flash</i>-based weblog to tell the world about your ever-growing collection of florescent feather boas or your serialized, Charles Dickens-style Great American Novel (Great British Novel just doesn&#8217;t have the same ring, sorry). Whatever it is, you plan on telling the world something about it each and every day.

</p><p>Well then, let&#8217;s think about this for a moment. Your user interface will be a Flash .swf file that will display content from your MySQL database. How do you want to organize your data? That&#8217;s really up to you. The simplest approach is the date-based model that most weblogs out there function on:one date, one title, one entry. Our simplest case calls for a table that contains the following information:

</p><p><img src="http://www.wired.com/wired/webmonkey/stuff/Flash_MySQL_chart1.gif" alt="Flash_MySQL_chart1.gif">

</p><p>Before we run off to create this table, let&#8217;s first look at some potential problems with our mock-up (remember: measure twice, cut once). While this table meets our most basic needs, we might want to include a few other things. Let&#8217;s say for instance that down road, when we get more sophisticated with our site, we want to be able to search according to subject. Well, right this minute we aren&#8217;t going to bother with a subject column, but in the future we might want to add a whole separate table to contain metadata of this sort. To link a new table to this one we&#8217;d need an index column. So our mock-up should include an ID column which will cover us if we&#8217;d ever like to add to our database. We&#8217;ll also be using the ID column to simplify the process of finding the newest entry.

</p><p><img src="http://www.wired.com/wired/webmonkey/stuff/Flash_MySQL_chart2.gif" alt="Flash_MySQL_chart2.gif">

</p><p>Alright, we&#8217;ve done all of our paperwork. Our database-to-be looks pretty robust, so let&#8217;s go ahead and create it.



</p>

<a name="Creating_the_Database"></a><h4> <span class="mw-headline">Creating the Database</span></h4>

<p>For this example, I&#8217;m going to assume you&#8217;re using the mysql client (note the all lowercase mysql, this denotes the client program that comes free with MySQL) in the command line. To fire up the mysql client, start up a new terminal window and login to your server using the format:<tt>/Path/To/mysql/ -h yourHostname -u yourUser -p</tt>. Enter your password when prompted. Now we&#8217;re going to issue the following commands (and don&#8217;t forget your semicolons):

</p>

<pre class="brush: js">mysql&gt; CREATE DATABASE blog_db;

</pre>

<p>This command tells MySQL to create a new database named blog_db (you can give it whatever name you like, just adjust everything accordingly). Now switch to the new database.

</p>

<pre class="brush: js">mysql&gt; USE blog_db;



</pre>

<p>You can verify that you&#8217;re actually using the blog_db by issuing a SELECT DATABASE() command which will tell basic information about our newly created blog_db database, namely, that it contains nothing. An empty database is a useless database, so let&#8217;s create a table. Your input will look like this:

</p>

<pre class="brush: js">CREATE TABLE blog_entries (



 id INT NOT NULL AUTO_INCREMENT ,



 date DATETIME NOT NULL ,



 title VARCHAR (30 )NOT NULL ,



 entry LONGTEXT NOT NULL ,



 PRIMARY KEY (id)



 );

</pre>

<p>OK what the hell is all that gibberish? Let&#8217;s walk through it one statement at a time.

</p><p>The CREATE statement should be obvious:It creates a new table by the name of blog_entries. Next, we fill out our table. But we don&#8217;t want just a table, we want to define our four columns that we&#8217;re going to use to organize our data. So, &#8220;id&#8221; is the first column and will be an integer, defined by INT(). The NOT NULL statement simply means that each row must have a value for this column. As you can see, I&#8217;ve set the table up to require values for all the columns. If you need some rows of a table left blank, simply change the statement to NULL which will allow blanks, or &#8220;null values&#8221; in database speak. The AUTO_INCREMENT statement tells MySQL to assign a new value for each row and to increment that number each time we enter another row. In other words, the first entry will get a value of 1, the second 2, and so on. This way, we don&#8217;t have to keep track of what entry number we&#8217;re on; we let MySQL do it for us. This will allow us to always find the most recent entry by querying for the largest number. This information will come in handy when we start writing queries in PHP.

</p><p>Next is DATETIME, a predefined format that will have MySQL stamp each entry with the current date and time. VARCHAR, on the next line, is short for variable character. This means that entries in the title column will be filled with characters of varying length. I chose to cut them off at 30 characters, but you can specify any number you&#8217;d like (up to 255). The last datatype we&#8217;re using is LONGTEXT. LONGTEXT allows up to 4,294,967,295 characters. That&#8217;s over one million words per entry &#8212; possibly overkill for our purposes, but I thought we&#8217;d play it safe. You could also use MEDIUMTEXT if you&#8217;re feeling less wordy than me. PRIMARY KEY is somewhat more complex, and I&#8217;m not going to explain it here, other than to say that if a column is AUTO_INCREMENTed it must be a primary key.

</p><p>Whew! Alright, just to make sure that MySQL created things the way we expect, issue the command DESCRIBE blog_entries and you should see the following:

</p><p><img src="http://www.wired.com/wired/webmonkey/stuff/Flash_MySQL_chart3.gif" alt="Flash_MySQL_chart3.gif">

</p><p>Notice the date format is year-month-day. Putting the year first takes some getting used to, but this is how MySQL handles dates &#8212; you&#8217;re just going to have to keep that in mind. We&#8217;re good monkeys, flexible and capable of adaptation.

</p>

<a name="Entering_Data"></a><h4> <span class="mw-headline">Entering Data</span></h4>

<p>Okay, we have our table all set up. Now we just need to enter some data. Entering information into MySQL can be very laborious when done by hand. For this reason, extensions were written to read from tab-delimited text files. However, since our table is pretty simple, and it&#8217;s unlikely that we&#8217;ll be entering more than one row at a time, I&#8217;m going to go ahead and enter things the old fashioned way. When your data gets more complex, you&#8217;ll want to investigate how to enter from external files. A good starting point would be the <a href="http://www.mysql.com/" class="external text" title="http://www.mysql.com/" rel="nofollow">MySQL site</a>.



</p>

<pre class="brush: js"> INSERT INTO blog_entries VALUES



 (



 '',NOW(),'my first blog entry','your text here'



 );



</pre>

<p>The main thing to notice here is that the first value is blank. The <i> value for the ID column tells MySQL to go ahead and insert the auto increment number, in this case, the integer one. The NOW() function gives us the current date and time. If you wanted to forge an older or newer date and time, you could enter them by hand in the format discussed earlier (YYYY-MM-DD 00:00:00). Double check to see that everything looks the way it should by issuing your first real query:</i>

</p>

<pre class="brush: js">SELECT * FROM blog_entries;

</pre>

<p>and you should see:

</p><p><img src="http://www.wired.com/wired/webmonkey/stuff/Flash_MySQL_chart4.gif" alt="Flash_MySQL_chart4.gif">

</p><p>I went ahead and inserted a few more entries to give us more to play with when we get to the Flash end of our blog. See, that wasn&#8217;t too bad was it? Alright, maybe a little, but take a deep breath and move on to the PHP anyway.

</p>

<a name="Add_a_Dash_of_PHP"></a><h4> <span class="mw-headline">Add a Dash of PHP</span></h4>



<p>When a user arrives at our blog, we want the following two things to happen:First, we want the latest entry to be displayed. Second, we want to display a list of past entries, which will be links to our older postings. I&#8217;m going to make the archives show both entry and date so you can see how both methods would work. The information we need to retrieve is stored in our table named &#8220;blog_entries&#8221;, which is part of the database named &#8220;blog_db&#8221;. The Flash piece we&#8217;re going to build will need to query the database for that information, and to do so, we will utilize a PHP file.

</p><p>If you&#8217;re familiar with Flash ActionScript, PHP should look familiar to you. Like ActionScript, PHP is a scripting language and therefore has a similar syntax. The one big difference from ActionScript is that PHP variables must always begin with a $. Just like in Actionscript, we&#8217;re going to write some functions and use them to interact with our blog_db database. The reason I spent so much time on the MySQL section is that the commands we used there to see the entries in our database are the same as the ones we&#8217;ll use in our PHP scripts. For our purposes, PHP is going to act as a middleman, sending queries from Flash to MySQL and then returning results back from MySQL to Flash.

</p><p>So, diving right in. Fire up your favorite text editor, create a new document and save it with the extension .php. Now enter in the following code. (<i>Your browser will probably wrap this code, so try copying the <a href="http://www.wired.com/wired/webmonkey/stuff/Flash_MySQL_phpcode1.txt" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/Flash_MySQL_phpcode1.txt" rel="nofollow">raw source</a></i>)

</p><p><br />

</p>

<pre class="brush: js">&lt;?php

mysql_pconnect ("yourHost", "yourUserName", "yourPassword");



mysql_select_db ("blog_db");

$qResult = mysql_query ("SELECT * FROM blog_entries ORDER BY id DESC");



$nRows = mysql_num_rows($qResult);

$rString ="&amp;n=".$nRows;





for ($i=0; $i&lt; $nRows; $i++){

	$row = mysql_fetch_array($qResult);

	$rString .="&amp;id".$i."=".$row['id']."&amp;"."&amp;title".$i."=".$row['title']."&amp;"."&amp;date".$i."=".$row['date']."&amp;"."&amp;entry".$i."=".$row['entry']."&amp;";

}

echo $rString."&amp;";



?&gt;



</pre>

<p><br />

Now let&#8217;s go through it line by line. The first few lines are PHP&#8217;s way of connecting to our database, just like what we did earlier in our terminal program. How does this work you ask? PHP, like ActionScript, has a bevy of built-in functions, and one of them is mysql_pconnect(). So then it&#8217;s just a matter of plugging in the right parameters for our database. The mysql_select_db() function is just like the USE function we typed earlier in our terminal. It tells MySQL which database we want to query. Then we have these lines:

</p>

<pre class="brush: js">$qResult = mysql_query ("SELECT * FROM blog_entries ORDER BY entry_id DESC");



 $nNows = mysql_num_rows($qResult);



 $rString = "&amp;n=".$Nrows;

</pre>

<p><br />

Here we&#8217;ve created three variables (remember variables in PHP must begin with a $). The variable $qResult is our actual query to the database (qResult is short for Query Result &#8212; get it?). The parameter is a string which tells MySQL to select all the information in our blog_entries table and return them in an ordered list. The ORDER BY command will order our result by the id column, starting with the largest number and reading down in descending order. This means that the rows of data returned start with the newest entry and read down to the oldest. Now you can see why we used the auto increment feature when we set up our table.

</p><p>The variable $nRows uses the function mysql_num_rows() to store the number of rows in our database (nRows is short for number of rows). We need to know how many rows we have so that we can write a loop to cycle through and read each row. Then we will write some code to format each row into a URL encoded string, which we will then pass on to our Flash movie. $rString is the variable we will use to pass the data to Flash (rString being my shorthand for Returned String). Next comes the loop to read all the data in our table.

</p>

<pre class="brush: js">for ($i=0; $i&lt; $nRows; $i++){



 	$row = mysql_fetch_array($qResult);



 	$rString .="&amp;id".$i."=".$row['id']."&amp;"."&amp;title".$i."=".$row['title']."&amp;".



 	"&amp;date".$i."=".$row['date']."&amp;"."&amp;file".$i."=".$row['entry']."&amp;";



 }



 echo $rString."&amp;";



</pre>

<p>&#8220;Oh my god!&#8221; you scream, &#8220;What is that string of nonsense?&#8221; Good question.

</p><p>The first thing we&#8217;ve done is set up a for loop. This loop says:for a variable $i, which is initially equal to zero, and for as long as $i remains less than our variable $nRows, increment the variable $i by one each time you perform the following loop. We do this so that PHP will loop through each row of our MySQL table and give each row its own unique number. This way when we pass the information to Flash, we can separate each entry and send it to the appropriate place.

</p><p>Next, we&#8217;ve taken advantage of another built-in PHP function (don&#8217;t worry &#8212; it won&#8217;t sue). We&#8217;ve created the variable $row and assigned it the function mysql_fetch_array(). Our parameter is the variable $qResult which we defined earlier as our query. This function takes the long string of information that is our variable $qResult and breaks it into an array. The new array contains all our table columns and the rows of data. Using the $row array we can access each element by name. Let&#8217;s just pause for a moment and consider that there are brilliant programmers out there who made this possible with one simple line of code.

</p><p>Done pausing? Great, let&#8217;s move on.

</p>

<a name="Strings.2C_Sealing_Wax.2C_Fancy_Stuff"></a><h4> <span class="mw-headline">Strings, Sealing Wax, Fancy Stuff</span></h4>

<p>OK now let&#8217;s concentrate on that really long and confusing line, the meat of our for loop. It turns out that Flash has to receive external information in the form of a URL-encoded string (actually, if you install Flash Remoting on your server, it can receive information as straight record sets, but Flash Remoting is beyond the scope of this article &#8212; visit the <a href="http://www.macromedia.com/software/flashremoting/" class="external text" title="http://www.macromedia.com/software/flashremoting/" rel="nofollow">Macromedia</a> site if you&#8217;re interested in learning more). The string our Flash movie will be looking for is a bunch of incremented variables squeezed between ampersands. If we include linebreaks to make it more readable it looks like this:

</p>

<pre class="brush: js">&amp;id0=1&amp;



 &amp;title0=myfirstEntry&amp;



 &amp;date0=2003:10:10 03:30:02&amp;



 &amp;entry0=some text&amp;

</pre>

<p>The variable $rString in our PHP code contains all the necessary formatting syntax to ensure that Flash gets this string. The PHP code looks confusing because we&#8217;re concatenating (joining together) strings (everything in quotes) with elements in our $row array.

</p><p>Let&#8217;s break it down some more. In PHP we write (I&#8217;ve put extra spaces between each element to make it easier to follow):

</p>

<pre class="brush: js"> $rString.=  "&amp;id".  $i.  "=".  $row['id'].  "&amp;"  et cetera...



</pre>

<p><br />

$rString is our PHP variable which will get passed to Flash. We&#8217;ve assigned it to a big long concatenated string of smaller strings and elements of the array $row. In PHP the . (dot) operator is used to concatenate elements of a string. &#8220;&amp;id&#8221; starts our string off and gets joined with the variable $i. Now the variable $i is the incremented element in our loop, so it will be an integer. Because we set $i=0 in our loop, the first time through the loop it will be 0, the second time it will be 1, and so on. For this reason, each row in our MySQL table has a unique identifying number. We then join the $i variable with an equals sign. So far we have given Flash the following information:

</p>

<pre class="brush: js"> &amp;id1=

</pre>

<p>Now we assign this newly created &#8220;id&#8221; variable an element in our $row array ($row[id]). Essentially we&#8217;re writing id=id, pretty simple right? The first number in our MySQL column was 1, so the first time through our loop we return a 1. We then tack on another string so that this element of our big string (the one being passed to Flash) is enclosed in ampersands the way we want it to be. All Flash is going to see is:

</p>

<pre class="brush: js"> &amp;id1=1&amp;

</pre>

<p>The rest of our variable $rString does the same formatting for the rest of our columns so that we can pass Flash our completed string which will look like this:

</p>

<pre class="brush: js"> &amp;id0=1&amp;&amp;title0=myfirstEntry&amp;&amp;date0=2003:10:10 03:30:02&amp;&amp;entry0=some text&amp;



</pre>

<p>Now for the final and really easy bit of code:

</p>

<pre class="brush: js">echo $rString."&amp;";



 ?&gt;

</pre>

<p>Since Flash is going to read the results of our PHP code, we have to make sure that we use the echo command, to tell PHP (when it gets done processing all the things we&#8217;ve told it to do) to display the completed string shown above. Echo is the same as print. In fact, you can use the command print if you so desire. The <tt>?&gt;</tt> simply closes our PHP code just like <tt>&nbsp;/html¢</tt> would close an HTML document.

</p><p>To test and make sure everything is working, upload the .php file to the server and point your browser to its location. You should be greeted by a stark white page with unformatted black text that reads:

</p>

<pre class="brush: js"> &amp;id0=1&amp;&amp;title0=myfirstEntry&amp;&amp;date0=2003:10:10 03:30:02&amp;&amp;entry0=some text&amp;



</pre>

<p>Okay, you&#8217;re done. With PHP that is. Time for a break. Crack your knuckles, lean back, smoke &#8216;em if you got &#8216;em, and relax. That was some terribly complicated stuff you just waded through.

</p><p>A quick note about security:Did it make you nervous to type your password in plain text at the beginning of our PHP file? It should. Granted, PHP is a server-side technology and there is no easy way to view this file as we&#8217;re seeing it. But that doesn&#8217;t mean it can&#8217;t be done. A more secure method of sending this information is to use an include statement. What we do is take the mysql_pconnect statement and move it to a separate file. Name it connect.inc, and now move it to a location on your server where the general public can&#8217;t access it. Then change the mysql_connect statement above to read include (&#8220;connect.inc&#8221;). Also, don&#8217;t forget to tell PHP where the include file is. We need to edit the PHP initialization file to point to the directory in which you just placed the include file. Typically, the initialization file lives in the <tt>/usr/local/apache/php</tt> directory. If your server isn&#8217;t running Apache, refer to your documentation. Not only is this method more secure, it saves you from having to type the whole connect statement every time you write a new PHP document for this database.

</p><p>Now rest up and get ready for <a href="/2010/02/Build_a_Website_With_Flash_and_MySQL_-_Lesson_2" title="Tutorial:Build a Website With Flash and MySQL - Lesson 2"> lesson 2</a>!

</p><p>

</p>



<div id="series">



<div class="series_hdr">From the series</div>

<table style="background: rgb(229, 249, 255) none repeat scroll 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" width="620">

<tbody><tr>

<td>

<p><strong class="selflink"> Build a Website With Flash and MySQL &#8211; Lesson 1</strong><br />

<a href="/2010/02/Build_a_Website_With_Flash_and_MySQL_-_Lesson_2" title="Tutorial:Build a Website With Flash and MySQL - Lesson 2"> Build a Website With Flash and MySQL &#8211; Lesson 2</a>

</p>

</td></tr></tbody></table>

</div><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/build_a_website_with_flash_and_mysql_-_lesson_1/feed/</wfw:commentRss>
        <slash:comments>2</slash:comments>

        
    </item>
    
    <item>
        <title>PHP and MySQL Tutorial &#8211; Lesson 3</title>
        <link>http://www.webmonkey.com/2010/02/php_and_mysql_tutorial_-_lesson_3/</link>
        <comments>http://www.webmonkey.com/2010/02/php_and_mysql_tutorial_-_lesson_3/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=737</guid>
        		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[Welcome to the third and final lesson for this tutorial. If you&#8217;ve gone through Lesson 1 and Lesson 2, you already know the essentials for installing and writing useful scripts with MySQL and PHP. We&#8217;re going to look at some useful PHP functions that should make your life a lot easier. First, let&#8217;s look at [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p>Welcome to the third and final lesson for this tutorial. If you&#8217;ve gone through <a href="/2010/02/PHP_and_MySQL_Tutorial_-_Lesson_1" title="Tutorial:PHP and MySQL Tutorial - Lesson 1"> Lesson 1</a> and <a href="/2010/02/PHP_and_MySQL_Tutorial_-_Lesson_2" title="Tutorial:PHP and MySQL Tutorial - Lesson 2"> Lesson 2</a>, you already know the essentials for installing and writing useful scripts with MySQL and PHP. We&#8217;re going to look at some useful PHP functions that should make your life a lot easier. First, let&#8217;s look at include files.

</p><p>We all know the basics of includes, right? Contents of an external file are referenced and imported into the main file. It&#8217;s pretty easy:You call a file and it&#8217;s included. When we do this in PHP there are two functions we need to talk about:<tt>include()</tt> and <tt>require()</tt>. The difference between these two functions is subtle but important, so let&#8217;s take a closer look. The <tt>require()</tt> function works in a XSSI-like way; files are included as part of the original document as soon as that file is parsed, regardless of its location in the script. So if you decide to place a <tt>require()</tt> function inside a conditional loop, the external file will be included even if that part of the conditional loop is false.</p>
<br />
<span id="more-737"></span>

<p><b>A Place for Everything</b>
</p><p>The <tt>include()</tt> function imports the referenced file each time it is encountered. If it&#8217;s not encountered, PHP won&#8217;t bother with it. This means that you can use <tt>include</tt> in loops and conditional statements, and they&#8217;ll work exactly as planned.

</p><p>Finally, if you use <tt>require()</tt> and the file you&#8217;re including does not exist, your script will halt and produce an error. If you use <tt>include()</tt>, your script will generate a warning, but carry on. You can test this yourself by trying the following script. Run the script, then replace <tt>include()</tt> with <tt>require()</tt> and compare the results.



</p>

<pre class="brush: js">&lt;html&gt;



&lt;body&gt;

&lt;?php

include("emptyfile.inc");

echo "Hello World";

?&gt;

&lt;/body&gt;

&lt;/html&gt;
</pre>

<p>I like to use the suffix .inc with my include files so I can separate them from normal PHP scripts. If you do this, make sure that you set your Web server configuration file to parse .inc files as PHP files. Otherwise, hackers might be able to guess the name of your include files and display them through the browser as text files. This could be bad if you&#8217;ve got sensitive information &#8211; such as database passwords &#8211; contained in the includes.

</p><p>So what are you going to do with include files? Simple! Place information common to all pages inside them. Things like HTML headers, footers, database connection code, and user-defined functions are all good candidates. Paste this text into a file called header.inc.

</p>

<pre class="brush: js">&lt;?php

$db = mysql_connect("localhost", "root");

mysql_select_db("mydb",$db);

?&gt;

&lt;html&gt;

&lt;head&gt;

&lt;title&gt;

&lt;?php echo $title&nbsp;?&gt;

&lt;/title&gt;

&lt;/head&gt;

&lt;body&gt;

&lt;center&gt;&lt;h2&gt;&lt;?php echo $title&nbsp;?&gt;&lt;/h2&gt;&lt;/center&gt;
</pre>

<p>Then create another file called footer.txt that contains some appropriate closing text and tags.

</p><p>Now let&#8217;s create a third file containing the actual PHP script. Try the following code, making sure that your MySQL server is running.

</p>

<pre class="brush: js">&lt;?php

$title = "Hello World";

include("header.inc");

$result = mysql_query("SELECT * FROM employees",$db);

echo "&lt;table border=1&gt;n";

echo "&lt;tr&gt;&lt;td&gt;Name&lt;/td&gt;&lt;td&gt;Position&lt;/tr&gt;n";

while ($myrow = mysql_fetch_row($result)) {

  printf("&lt;tr&gt;&lt;td&gt;%s&nbsp;%s&lt;/td&gt;&lt;td&gt;%s&lt;/tr&gt;n", $myrow[1], $myrow[2], $myrow[3]);

}

echo "&lt;/table&gt;n";

include("footer.inc");

?&gt;
</pre>

<p>See what happens? The include files are tossed into the main file and then the whole thing is executed by PHP. Notice how the variable <tt>$title</tt> was defined before header.inc is referenced. Its value is made available to the code in header.inc; hence, the title of the page is changed. You can now use header.inc across all your PHP pages, and all you&#8217;ll have to do is change the value of <tt>$title</tt> from page to page.

</p><p>Using a combination of includes, HTML, conditional statements, and loops, you can create complex variations from page to page with an absolute minimum of code. Includes become especially useful when used with functions, as we&#8217;ll see down the road.On to the exciting world of data validation.


<a name="Simple_Validation"></a><h4> <span class="mw-headline">Simple Validation</span></h4>

<p>Imagine for a moment that we&#8217;ve got our database nicely laid out and we&#8217;re now requesting information from users that will be inserted into the database. Further, let&#8217;s imagine that you have a field in your database waiting for some numeric input, such as a price. Finally, imagine your application falling over in a screaming heap because some smart aleck put text in that field. MySQL doesn&#8217;t want to see text in that portion of your SQL statement &#8211; and it complains bitterly.

</p><p>What to do? Time to validate.

</p><p>Validation simply means that we&#8217;ll examine a piece of data, usually from an HTML form, and check to make sure that it fits a certain model. This can range from ensuring that a element is not blank to validating that an element meets certain criteria (for example, that a numeric value is stipulated or that an email address contains an @ for an email address).

</p><p>Validation can be done on the server side or on the client side. PHP is used for server-side validation, while JavaScript or another client-based scripting language can provide client-side validation. This article is about PHP, so we&#8217;re going to concentrate on the server end of things.

</p><p>Let&#8217;s ignore our database for the moment and concentrate on PHP validation. If you wish, you can add additional fields to our employee database quite simply by using the MySQL <a href="http://www.mysql.com/Manual_chapter/manual_Reference.html#ALTER_TABLE" class="external text" title="http://www.mysql.com/Manual_chapter/manual_Reference.html#ALTER_TABLE" rel="nofollow">ALTER statement</a> &#8211; that is, if you want to commit to the values that we&#8217;ll validate.

</p><p>There are several useful PHP functions we can use to validate our data, and they range from simple to highly complex. A simple function we could use might be <tt>strlen()</tt>, which tells us the length of the variable.

</p><p>A more complex function would be <tt>ereg()</tt>, which uses full regular expression handling for complex queries. I won&#8217;t delve into the complexities of regex here, as entire books have been written on the subject, but I will provide some examples on the next page.



</p><p>Let&#8217;s start with a simple example. We&#8217;ll check to see whether a variable does or does not exist.

</p>

<pre class="brush: js"> &lt;html&gt;

 &lt;body&gt;

 &lt;?php

 if ($submit) {

      if (!$first ||&nbsp;!$last) {

 	$error = "Sorry! You didn't fill in all the fields!";

 	} else {

 		// process form

 		echo "Thank You!";
 	}
 }

 if (!$submit || $error) {

      echo $error;

     &nbsp;?&gt;

      &lt;P&gt;

      &lt;form method="post" action="&lt;?php echo $PHP_SELF&nbsp;?&gt;"&gt;

      FIELD 1:&lt;input type="text" name="first" value="&lt;?php echo $first&nbsp;?&gt;"&gt;

      &lt;br&gt;

      FIELD 2:&lt;input type="text" name="last" value="&lt;?php echo $last&nbsp;?&gt;"&gt;

      &lt;br&gt;

      &lt;input type="Submit" name="submit" value="Enter Information"&gt;

      &lt;/form&gt;

      &lt;?php

 } // end if

 ?&gt;

 &lt;/body&gt;

 &lt;/html&gt;

</pre>

<p>The keys to this script are the nested conditional statements. The first checks to see whether the Submit button has been pressed. If it has, it goes on to check that both the variables <tt>$first</tt> and <tt>$last</tt> exist. The || symbol means &#8220;or&#8221; and the&nbsp;! symbol means &#8220;not.&#8221; We could also rewrite the statement to say, &#8220;If $first does not exist or $last does not exist, then set $error to the following.&#8221;

</p><p>Next, let&#8217;s extend things a little by checking to see whether a string is a certain length. This would be ideal for passwords, since you don&#8217;t want some lazy user entering a password of only one or two letters. You&#8217;d rather it be, say, six or more characters.

</p><p>The function for this is, as you already know, <tt>strlen()</tt>. It simply returns a number equal to the number of characters in the variable being tested. Here, I modified the script above to check the length of <tt>$first</tt> and <tt>$last</tt>.

</p>

<pre class="brush: js"> &lt;html&gt;

 &lt;body&gt;

 &lt;?php

 if ($submit) {

      if (strlen($first) &lt; 6 || strlen($last) &lt; 6) {

 	$error = "Sorry! You didn't fill in all the fields!";

 	} else {

 		// process form

 		echo "Thank You!";

 	}

 }

 if (!$submit || $error) {

      echo $error;

     &nbsp;?&gt;

      &lt;P&gt;

      &lt;form method="post" action="&lt;?php echo $PHP_SELF&nbsp;?&gt;"&gt;

      FIELD 1:&lt;input type="text" name="first" value="&lt;?php echo $first&nbsp;?&gt;"&gt;

      &lt;br&gt;

      FIELD 2:&lt;input type="text" name="last" value="&lt;?php echo $last&nbsp;?&gt;"&gt;

      &lt;br&gt;

      &lt;input type="Submit" name="submit" value="Enter Information"&gt;

      &lt;/form&gt;

      &lt;?php

 } // end if

 ?&gt;

 &lt;/body&gt;

 &lt;/html&gt;

</pre>

<p>Run this script and try entering six or fewer letters to see what happens. It&#8217;s simple yet quite effective.

</p>

<a name="Not-So-Simple_Validation"></a><h4> <span class="mw-headline">Not-So-Simple Validation</span></h4>

<p>Let&#8217;s talk a bit about using regular expressions with the <tt>ereg()</tt> and <tt>eregi()</tt> functions. As I said earlier, these can be either quite complex or very simple, depending on what you need.

</p><p>Using regular expressions, you can examine a string and intelligently search for patterns and variations to see whether they match the criteria you set. The most common of these involves checking whether an email address is valid (although, of course, there&#8217;s no fail-safe way of doing this).

</p><p>Rather than delve into the mysteries of regular expressions, I&#8217;ll provide some examples. You can use the same form we created on the previous page &#8211; just paste in the lines below to see how they work.

</p><p>First, let&#8217;s make sure that text only has been entered into a form element. This regular expression tests true if the user has entered one or more lowercase characters, from a to z. No numbers are allowed:

</p>

<pre class="brush: js"> if (!ereg("[a-Z]", $first) ||&nbsp;!ereg("[a-Z]", $last)) { </pre>

<p>Now, let&#8217;s extend this expression to check whether the string is four to six characters in length. Using <tt><a href="/special?title=Alpha:&amp;action=edit" class="new" title="Alpha:">alpha:</a></tt> is an easy way to check for valid alphabetic characters. The numbers in the braces check for the number of occurrences. And note that the ^ and $ indicate the beginning and end of the string.

</p>

<pre class="brush: js"> if (!ereg("^[[:alpha:]]{4,6}$", $first) ||&nbsp;!ereg("^[[:alpha:]]{4,6}$", $last)) { </pre>

<p>Finally, let&#8217;s build a regular expression that will check an email address&#8217; validity. There&#8217;s been plenty of discussion about the effectiveness of checking for email addresses in this way. Nothing&#8217;s completely foolproof, but what I have below works pretty well.

</p><p>I took this gem from the PHP <a href="http://www.progressive-comp.com/Lists/?l=php3-general#php3-general" class="external text" title="http://www.progressive-comp.com/Lists/?l=php3-general#php3-general" rel="nofollow">mailing list</a>. It&#8217;s a great resource &#8211; use it. And yes, this is as scary as it looks.

</p>

<pre class="brush: js">	if (!ereg('^[-!#$%&amp;'*+./0-9=?A-Z^_`a-z{|}~]+'.

'@'.

'[-!#$%&amp;'*+/0-9=?A-Z^_`a-z{|}~]+.'.

'[-!#$%&amp;'*+./0-9=?A-Z^_`a-z{|}~]+$', $last)) {

</pre>

<p>Don&#8217;t spend too much time looking at this. Just move on to the next bit.

</p>

<a name="Functions"></a><h4> <span class="mw-headline">Functions</span></h4>

<p>Enjoy that last regex expression? Fun, wasn&#8217;t it? Wouldn&#8217;t it be even more fun to enter that chunk on a dozen different pages that need to process email addresses?! Think about the joy of finding a typo in that mess &#8211; and doing it a dozen times no less. But of course, there&#8217;s a better way.

</p><p>Remember when we talked about include files earlier in this lesson? They&#8217;ll allow us to create a piece of code like the email checker and include it multiple times across several pages. This way, when we want to change the code, we need edit only one file, not many.

</p><p>But if we want to get this done, we&#8217;ll have to use functions.

</p><p>We&#8217;ve already used functions plenty of times. Every time we query the database or check the length of a string we&#8217;re using functions. These functions are built into PHP. If you&#8217;re a keen coder, you can extend PHP with your own customized functions. But that&#8217;s a bit advanced for this tutorial. Instead we&#8217;ll create functions that will reside within our PHP script.

</p><p>A function is simply a block of code that we pass one or more values to. The function then processes the information and returns a value. The function can be as simple or complex as we like, but as long as we can pass a value in and get one out, we don&#8217;t really care how complex it is. That&#8217;s the beauty of functions.

</p><p>Functions in PHP behave similarly to functions in C. When we define the functions, we must specify what values the function can expect to receive. It&#8217;s tricky to get a handle on at first, but it prevents weird things from happening down the road. This is done because the variables inside a function are known as private variables. That is, they exist only inside the function. You may, for instance, have a variable in your script called <tt>$myname</tt>. If you created a function and expected to use the same <tt>$myname</tt> variable (with the same value), it wouldn&#8217;t work. Alternatively, you could have the variable <tt>$myname</tt> in your script and also create another variable called <tt>$myname</tt> in your function, and the two would co-exist quite happily with separate values. I do not recommend doing this, however! When you come back and edit it six months later, you&#8217;ll be breaking things left and right. There are exceptions to this rule as with all things, but that&#8217;s outside the scope of this article.



</p><p>So let&#8217;s create a function. We&#8217;ll start simply. We need to give the function a name and tell it what variables to expect. We also need to define the function before we call it.

</p>

<pre class="brush: js"> &lt;html&gt;
 &lt;body&gt;

 &lt;?php

 function  addnum($first, $second) {

 	$newnum = $first + $second;

	return $newnum;

 }

 echo addnum(4,5);

 ?&gt;

 &lt;/body&gt;

 &lt;/html&gt;

</pre>

<p>That&#8217;s it! First, we created our function. Notice how we defined two new variables, called <tt>$first</tt> and <tt>$second</tt>. When we call the function, each variable is assigned a value based on the order in which it appears in the list &#8211; 4 goes to <tt>$first</tt>, 5 to <tt>$second</tt>. Then we simply added the two numbers together and returned the result. &#8220;Return&#8221; here simply means to send the result back. At the end of the script we print the number 9.

</p><p>Let&#8217;s create something that&#8217;s more useful to our database application. How about something that gracefully handles errors? Try this:

</p>

<pre class="brush: js"> &lt;html&gt;
 &lt;body&gt;

 &lt;?php

 function  do_error($error) {

 	echo  "Hmm, looks like there was a problem here...&lt;br&gt;";

 	echo "The reported error was $error.n&lt;br&gt;";

 	echo "Best you get hold of the site admin and let her know.";

 	die;
 }

 if (!$db = @mysql_connect("localhost","user", "password")) {

 	$db_error = "Could not connect to MySQL Server";

 	do_error($db_error);

 }

 ?&gt;

 &lt;/body&gt;
 &lt;/html&gt;
</pre>

<p>Before running this, try shutting down MySQL or using a bogus username or password. You&#8217;ll get a nice, useful error message. Observant readers will notice the @ symbol in front of <tt>mysql_connect()</tt>. This suppresses error messages so that you get the information only from the function. You&#8217;ll also see we were able to pass a variable into the function, which was defined elsewhere.

</p><p>Remember that I said functions use their own private variables? That was a little white lie. In fact, you can make variables outside of a function accessible to the function. You might create a function to query a database and display a set of results over several pages. You don&#8217;t want to have to pass the database connection identifier into the function every time. So in this situation, you can make connection code available as a global variable. For example:

</p>

<pre class="brush: js">

 &lt;html&gt;

 &lt;body&gt;

 &lt;?php

 function  db_query($sql) {

 	global $db;

 	$result = mysql_query($sql,$db);

 	return $result;

 }

 $sql = "SELECT * FROM mytable";

 $result = db_query($sql);

 ?&gt;

 &lt;/body&gt;

 &lt;/html&gt;
 </pre>

<p>This is a basic function, but the point is that you don&#8217;t need to send <tt>$db</tt> through when you call the function &#8211; you can make it available using the word global. You can define other variables as global in this statement, just separate the variable names by a comma.

</p><p>Finally, you can look like a real pro by using optional function variables. Here, the key is to define the variable to some default in the function, then when you call the function without specifying a value for the variable, the default will be adopted. But if you do specify a value, it will take precedence.

</p><p>Confused? For example, when you connect to a database, you nearly always connect to the same server and you&#8217;ll likely use the same username and password. But sometimes you&#8217;ll need to connect to a different database. Let&#8217;s take a look.

</p>

 <pre class="brush: js"> &lt;html&gt;
 &lt;body&gt;
 &lt;?php

 function  db_connect($host = "localhost", $user="username", $pass="graeme") {

 	$db = mysql_connect($host, $username, $password);

 	return $db;

 }

 $old_db = db_connect();

 $new_host = "site.com";

 $new_db = db_connect($new_host);

 ?&gt;

 &lt;/body&gt;

 &lt;/html&gt;
 </pre>

<p>Isn&#8217;t that cool? The variables used inside the function were defined when the function was defined. The first time the function is called, the defaults are used. The second time, we connect to a new host, but with the same username and password. Great stuff!

</p><p>Think about where you could use other functions in your code. You could use them for data checking, performing routine tasks, and so on. I use them a lot when processing text for display on a Web page. I can check, parse, and modify the text to add new lines and escape HTML characters in one fell swoop.

</p><p>Now all that&#8217;s left to do is to impart some words of wisdom.

</p>

<a name="Closing_Advice"></a><h4> <span class="mw-headline">Closing Advice</span></h4>

<p>When it comes to databasing, there&#8217;s a lot to learn. If you haven&#8217;t done it already, find a good book about database design and learn to put together a solid database &#8211; on any platform. It&#8217;s an invaluable skill and it will save you plenty of time and headache in the long run. Also, learn about MySQL. It&#8217;s a complex but interesting database with a wealth of useful documentation. Learn about table structure, data types, and SQL. You can actually achieve some pretty impressive stuff if you know enough SQL.

</p><p>Finally, there&#8217;s PHP. The PHP Web site has nearly everything you need, from a comprehensive manual to mailing-list archives to code repositories. An excellent way to learn about PHP is to study the examples used in the manual and to check out the code archives. Many of the posted scripts consist of functions or classes that you can use for free in your own scripts without having to reinvent the wheel. Additionally, the mailing list is an excellent spot to check out if you get stuck. The developers themselves read the list and there are plenty of knowledgeable people there who can help you along the way.

</p><p>Good luck and good coding!

</p>

<ul><li><a href="/2010/02/PHP_and_MySQL_Tutorial" title="Tutorial:PHP and MySQL Tutorial"> PHP and MySQL Tutorial</a>

</li><li><a href="/2010/02/PHP_and_MySQL_Tutorial_-_Lesson_1" title="Tutorial:PHP and MySQL Tutorial - Lesson 1"> PHP and MySQL Tutorial &#8211; Lesson 1</a>

</li><li><a href="/2010/02/PHP_and_MySQL_Tutorial_-_Lesson_2" title="Tutorial:PHP and MySQL Tutorial - Lesson 2"> PHP and MySQL Tutorial &#8211; Lesson 2</a>

</li><li><strong class="selflink"> PHP and MySQL Tutorial &#8211; Lesson 3</strong>

</li></ul>

<p><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/php_and_mysql_tutorial_-_lesson_3/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>

        
    </item>
    
    <item>
        <title>Drizzle Wants to Make MySQL Sizzle</title>
        <link>http://www.webmonkey.com/2008/07/drizzle_wants_to_make_mysql_sizzle/</link>
        <comments>http://www.webmonkey.com/2008/07/drizzle_wants_to_make_mysql_sizzle/#comments</comments>
        <pubDate>Wed, 23 Jul 2008 13:56:41 +0000</pubDate>

                <dc:creator>Scott Gilbertson</dc:creator>

        <guid isPermaLink="false">http://www.webmonkey.com/blog/drizzlewantstomakemysqlsizzle</guid>
        		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software & Tools]]></category>
		<category><![CDATA[MySQL]]></category>
        <description><![CDATA[There&#8217;s some potentially interesting changes coming to the world of MySQL. And no, it&#8217;s got nothing to do with the recent acquisition by Sun Microsystems. Drizzle is a new project from Brian Aker, MySQL&#8217;s director of architecture, which aims to take MySQL and strip out the fat, leaving a faster InnoDB and UTF8-supporting database designed [...]]]></description>

            <content:encoded><![CDATA[<p><!-- wpautop enabled -->
<p><img alt="Mysql" title="Mysql" src="http://blog.wired.com/photos/uncategorized/2007/04/25/mysql.jpg" />There&#8217;s some potentially interesting changes coming to the world of MySQL. And no, it&#8217;s got nothing to do with the recent <a href="http://www.webmonkey.com/blog/Sun_Shines_the_%241_Billion_Light_on_MySQL_Acquisition">acquisition by Sun Microsystems</a>. </p>
<p><a href="http://krow.livejournal.com/602409.html">Drizzle</a> is a new project from Brian Aker, MySQL&#8217;s director of architecture, which aims to take MySQL and strip out the fat, leaving a faster InnoDB and UTF8-supporting database designed for today&#8217;s web apps.</p>
<p>Drizzle will get rid of query caches, stored procedures, permissions, views, and triggers; it will offer only simplified field types and it will be optimized for the small subset of features that are commonly used in web apps. </p>
<p>It isn&#8217;t intended to replace MySQL, but it could end up being, as Simon Willison <a href="http://simonwillison.net/2008/Jul/23/drizzle/">suggests</a>, MySQL&#8217;s Firefox. </p>
<p>Today&#8217;s web apps are generally written with frameworks like Ruby on Rails, Django and the like, all of which include things like sanitized database queries and more. So bother with prepared statements or other expensive (performance-wise) database server tools? </p>
<p>The project is still young and there&#8217;s no code to download yet, nor any hard and fast performance numbers, but it definitely looks like one to keep an eye on.</p>
<p><strong>See Also:</strong><br/></p>
<ul>
<li><a href="http://www.webmonkey.com/blog/Sun_Shines_the_%241_Billion_Light_on_MySQL_Acquisition">Sun Shines the $1 Billion Light on MySQL Acquisition</a></li>
<li><a href="http://www.webmonkey.com/blog/Community_Cries_Foul_Over_Sun_s_Possible_Plans_For_MySQL">Community Cries Foul Over Sun&#8217;s Possible Plans For MySQL</a></li>
<li><a href="http://www.webmonkey.com/blog/Sun_Changes_Its_Mind__MySQL_Tools_to_Remain_Open_Source">Sun Changes Its Mind, MySQL Tools to Remain Open Source</a></li>
<li><a href=http://www.webmonkey.com/blog/Google_Releases_MySQL_Improvements">Google Releases MySQL Improvements</a></li>
</ul>
<div id='linker_widget' class='contextly-widget'></div>
]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2008/07/drizzle_wants_to_make_mysql_sizzle/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>

        
    </item>
    
    <item>
        <title>Drupal&#8217;s Creator Envisions Web Publishing&#8217;s Plug-and-Play Future</title>
        <link>http://www.webmonkey.com/2008/06/drupal_s_creator_envisions_web_publishing_s_plug-and-play_future/</link>
        <comments>http://www.webmonkey.com/2008/06/drupal_s_creator_envisions_web_publishing_s_plug-and-play_future/#comments</comments>
        <pubDate>Thu, 19 Jun 2008 22:29:01 +0000</pubDate>

                <dc:creator>Michael Calore</dc:creator>

        <guid isPermaLink="false">http://www.webmonkey.com/blog/drupalscreatorenvisionswebpublishingsplugandplayfuture</guid>
        		<category><![CDATA[Business]]></category>
		<category><![CDATA[Software & Tools]]></category>
		<category><![CDATA[CMS]]></category>
		<category><![CDATA[drupal]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
        <description><![CDATA[Dries Buytaert started down his path to fame when he coded up a private message board for his college dormitory. Nine years later, that modest bulletin board software package has grown into Drupal, one of the most popular open-source content publishing systems on the web with thousands of active contributors. In March 2008, Buytaert connected [...]]]></description>

            <content:encoded><![CDATA[<p><!-- wpautop enabled -->
<p><img class="blogimg" src="http://howto.wired.com/mediawiki/images/Dries_acquia_630.jpg" alt="Dries Buytaert CTO of Acquia and Drupal project lead" title="Dries Buytaert CTO of Acquia and Drupal project lead" class="full" /></p>
<p>Dries Buytaert started down his path to fame when he coded up a private message board for his college dormitory. Nine years later, that modest bulletin board software package has grown into <a href="http://drupal.org/">Drupal</a>, one of the most popular open-source content publishing systems on the web with thousands of active contributors. In March 2008, Buytaert connected with entrepreneur Jay Batson, and together the two of them founded <a href="http://acquia.com/">Acquia</a>, a commercial venture that will provide technical support for Drupal&#8217;s devotees as well as further the adoption and development of the platform.</p>
<p>Webmonkey sat down with Dries and Jay to talk about the history of Drupal, where development is headed and the role their new company will play in the project&#8217;s future.</p>
<p><em>Photos: Jim Merithew/Wired</em></p>
<p><strong>Webmonkey:</strong> Dries, can you give us Drupal&#8217;s back-story? The germ of the idea and how the platform grew into existence?</p>
<p><strong>Dries Buytaert:</strong> It sort of happened by accident. I was a student at the University of Antwerp in Belgium around 1999. I was doing web development with CGI and server-side includes, but I wanted to learn more about technologies like PHP and MySQL. Also, at the same time, we had the need for an internal messaging system at our student dorm. So, I wrote a simple message board. Then when I graduated, I decided to move my internal message board onto the internet.</p>
<p>When I registered a domain for it, I wanted to register the name &#8220;Dorp,&#8221; which is Dutch for &#8220;small village.&#8221; But I mis-typed, and actually ended up registering the name Drop. Amazingly, Drop.org was still available, and since it&#8217;s an English word with multiple meanings, I decided to just go with it.</p>
<p>Our original user community died pretty quickly, but I continued working on it by adding things like RSS feeds and the ability for users to rate content. More and more people started coming to the site with ideas and suggestions, like ways to modify the algorithm that handles comment moderation. At a certain point, I was getting so many suggestions that I decided to just open up the source code. That was the Drupal 1.0 release, which came out in early 2001.</p>
<p>At the time of the release, I was fairly confident that I had a good system. I felt that it was competitive with the other open source technologies out there like PHP-Nuke. So, it felt like the right thing to do.</p>
<p><strong>Webmonkey:</strong> One of the key pieces of Drupal&#8217;s design is its modularity &#8212; users install a core package, then add functionality by installing task-specific modules. Where did the idea for the modular design originate?</p>
<p><strong>Buytaert:</strong> It was part of the initial design. I was sort of shocked that most of the other systems didn&#8217;t have a modular design &#8212; to me, with my background as a computer science student, that felt like a very natural thing to do. I was also involved in the Linux kernel back then, working on wireless network drivers. That&#8217;s also obviously a modular system, so I may have gotten some inspiration from there as well.</p>
<p><a href="http://howto.wired.com/mediawiki/images/Dries_jay_acquia_630.jpg" border="0"><img class="blogimg" src="http://howto.wired.com/mediawiki/images/Dries_jay_acquia.jpg" title="Buytaert and Batson CLICK FOR LARGER" alt="Buytaert and Batson CLICK FOR LARGER" border="0" /></a><strong>Jay Batson:</strong> Speaking as somebody who dealt with a lot of content management systems before meeting Dries, I can say that most of the other CMS&#8217;s out there didn&#8217;t come from people who were computer science grad-types. They were built by web designers or programmers who maybe were self-taught and had hacked together a system that sort of worked. They didn&#8217;t come from people with an underlying discipline of computer science. That ended up being a key distinction between Drupal and other systems.</p>
<p><strong>Webmonkey:</strong> Drupal is especially popular with those who want to build a site around some sort of central social networking component. Is that because it gives such granular control over user management, or is it because Drupal became popular at the same time social networks were really taking off?</p>
<p><strong>Buytaert:</strong> I think the first reason is definitely a big part of it. Drupal was a multi-user system from day one, but most of the other systems are behind Drupal as far as user management and access rights.</p>
<p>It&#8217;s a very social system by design. For example, the original Drop.org site was very much like Digg, where people could submit links and vote on each other&#8217;s submissions. Such user interaction was a key initial feature of Drupal. Over time, we&#8217;ve been moving away from these features. That voting system has since been taken out of the core, but it&#8217;s available in a module. Instead we&#8217;re evolving into a platform that can do more &#8212; the traditional web content management stuff as well as the social stuff.</p>
<p><strong>Batson:</strong> They also got a good boost because Drupal 5 had as its tag line &#8220;Community Plumbing.&#8221; At that moment in time when community-based sites were becoming more important, here was this system marketing itself as being optimized for that.</p>
<p>Also at that time, there were a lot of people coming into the Drupal community and contributing code. So, a great deal of code was written in that area with the social features in mind. I know Dries was spending most of his time during that period managing those contributions &#8212; keeping the Drupal core slim, but making sure that the key features were there. And, at the same time, stressing the importance of modules.</p>
<p><strong>Buytaert:</strong> One of the things I&#8217;ve always encouraged people to do was take Drupal in different directions. I think it&#8217;s a very powerful notion to get out of people&#8217;s way. So if they want to build a social networking site or a Flickr clone, I think it&#8217;s important that Drupal as a platform is capable of serving all these different needs. That&#8217;s what the modular design helps accomplish.</p>
<p><strong>Webmonkey:</strong> Tell us about Acquia, the company you founded together.</p>
<p><strong>Batson:</strong> Our goal is to become to Drupal what Red Hat and Canonical are to Linux. If you want a supported version of this open-source software, you come to us and pay a subscription. You get a distribution, a set of services for maintenance and updates plus access to our tech support center. So let&#8217;s say you&#8217;re running a large-scale media site and you&#8217;ve built all of your front-end infrastructure on Drupal. You need an answer about something, and you want the ability to pick up the phone and have an answer within an hour rather than send an e-mail and wait a day, or wait for the appropriate person to log in on IRC. On the other end of the spectrum is the small site that needs help with installing modules or managing updates. It&#8217;s a well-proven open-source business model.</p>
<p>The other role we can play at Acquia is supporting the Drupal development community. Drupal has wonderful organic growth. The community is roughly doubling every year. That&#8217;s impressive, but we&#8217;d like to see it grow by a factor of ten.</p>
<p><strong>Webmonkey:</strong> How many developers are working on Drupal right now?</p>
<p><strong>Buytaert:</strong> For Drupal 6, the last major release, we had around 900 people contribute to the core. As a reference, that&#8217;s the same number of people who contribute to the Linux kernel. There are over 2,000 contributed modules, and each of these modules has one or more maintainers. The Drupal.org website has between 250,000 and 300,000 registered users. These are not necessarily all developers, but those people are participating in the community in some way.</p>
<p><strong>Webmonkey:</strong> Where is Drupal development going next?</p>
<p><strong>Buytaert:</strong> We are working on Drupal 7 right now. We&#8217;ll have a better database abstraction layer, better support for WYSIWYG tools and usability improvements for admins that make it easier to configure Drupal.</p>
<p>We have a new core feature called Content Construction Kit, or CCK. This lets you define new types of content using a web interface. For example, if you have a bicycle website and you want your users to be able to share their favorite rides, you can create a new content type called &#8220;rides.&#8221; That content type might include a start location, an end location, a link to a Google map, some pictures of the route, text describing the ride. Once you have all of this data, you can choose to visualize the ride on a Google map, or display it all in a table or whatever you want. Many different views can be extracted from this big bag of user data, and it can all be accomplished using an easy web interface.</p>
<p>Our long-term vision for Drupal as an open-source project to fully democratize online publishing &#8212; to make it possible for everyone to create really powerful and interesting websites just by clicking around. Drupal lets you get a working prototype up and running in just a couple of hours without having to write any code. That&#8217;s very powerful.</p>
<div id='linker_widget' class='contextly-widget'></div>
]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2008/06/drupal_s_creator_envisions_web_publishing_s_plug-and-play_future/feed/</wfw:commentRss>
        <slash:comments>2</slash:comments>

        
    </item>
    </channel>
</rss>