TweetFollow Us on Twitter

PHP And MySQL, Together At Last

Volume Number: 21 (2005)
Issue Number: 6
Column Tag: Programming

Getting Started

PHP And MySQL, Together At Last

by Dave Mark

Interwoven in my last six columns or so were columns that showed you how to install and test PHP and MySQL. The PHP and MySQL columns all dealt with PHP and MySQL in isolation. The PHP code did not access a MySQL database, and the MySQL database access was all done via the Terminal and not via a PHP encrusted web page. In this month's column, we'll verify that both are installed and available, then see if we can't make them play nicely together. Let's start by verifying our install.

Checking Your PHP Install

If you are new to PHP, make your way over to http://www.php.net and browse through their documentation. If you've installed even a reasonably recent version of Mac OS X on your machine, you should have PHP installed. One solid clue that you do have PHP installed can be obtained by typing this command in Terminal:

$ ls /usr/local/

If the result of this command includes the text "php5", chances are, you're all set. If it doesn't, visit Mark Liyanage's wonderful PHP site:

http://www.entropy.ch/software/macosx/php/

Mark has put together an excellent PHP resource for Mac OS X and he does a nice job keeping it up to date. Though, at this writing, the site still lists Mac OS X 10.3 as the most recently supported, I had no trouble using his install package on my Tiger machine. Obviously, you'll want to backup your machine first, just in case something does go wrong.

Hopefully, you do have PHP installed on your machine already. Regardless of how you got there, once you've got PHP 5 installed, here's a simple test to make sure you're all good.

Launch your favorite text editor, be sure it is set to save as plain-text, create a new file, then enter this text:

<?php
phpinfo()
?>

Save the file as test.php and place it in the Sites subfolder of your home folder (inside ~/Sites/, aka, /Users/xxxx/Sites/).

To test your new PHP file, launch Safari and type:

http://127.0.0.1/~davemark/test.php

Obviously, you'll replace "davemark" with your own user name. Safari will ask your Apache server to pass the referenced file on to the PHP pre-processor. If all is kosher, a giant table will appear in a Safari window. The beginning of my giant table is shown in Figure 1.


Figure 1. The PHP info table.

Note that my computer is running PHP version 5.0.4. You'll definitely want to check on http://php.net to see if there's a later version available.

Checking Your MySQL Install

If you are new to MySQL, check out http://www.mysql.com. In the March, 2005 Getting Started column, I went through the process of hunting down the proper package for your version of Mac OS X, installing MySQL, starting and shutting down the MySQL server, and setting up the accounts and passwords.

Then, in the April Getting Started, we used the MySQL monitor application, running in Terminal, to build a database and, within that, a table. We added to and deleted rows from the table, and ran some queries to report on the table data. Obviously, I don't want to repeat all that here, but I thought it would be worth repeating a few of the basics, just to make sure we were on the same page.

Start by making sure you have an alias set up for mysql. In Terminal, type this command:

alias

This will list your aliases. Hopefully, one of your aliases will be:

alias mysql='/usr/local/mysql/bin/mysql'

If not, edit the file .profile in your home directory and add this line to the end of it:

alias mysql='/usr/local/mysql/bin/mysql'

Now quit and re-launch Terminal, which will re-execute the commands in .profile. Now, when you type the alias command, your alias should appear. This lets us type mysql to launch the MySQL monitor.

Launch the monitor by typing:

mysql -u root -p

As a reminder, you are launching the monitor with a user of root. You'll be prompted for a password. Type in the password you created when you created your account. Remember, this root is not the same root as your Mac root account. If you are having trouble logging in as root, go back to your setup instructions or to the March Getting Started.

Here's what my monitor looks like:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.12-standard

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

If mysql does not launch your MySQL monitor, either your alias is not set correctly (in which case, go check to see if you've got a file called mysql in the directory /usr/local/mysql/bin/) or you did not install MySQL correctly. If MySQL was not installed correctly, get hold of the March MacTech and follow the installation process, or make your way through the MySQL installation instructions on http://mysql.com.

Assuming your monitor comes up as mine did, type this command:

show databases;

Don't foget the ending semicolon. Here's my result:

mysql> show databases;
+----------+
| Database |
+----------+
| test     |
+----------+
1 row in set (0.18 sec)

mysql>

If you've played with MySQL, you may find yourself with a different set of databases. Not a problem. As long as the command works, you're fine, no matter the result.

Driving MySQL From Within PHP

In April's column, we used the MySQL monitor to create a database, add rows, delete rows, and update values in a table. In the remainder of this month's column, we're going to do the same sorts of things, but do them from within PHP, instead of from the monitor.

Before we get into our PHP example, let's use the monitor to set up a database and table, then populate the table. This approach is pretty typical: Set up the database and table using the monitor, then query/populate the table from your PHP/web interface.

In the monitor, type this command:

mysql> create database products;
Query OK, 1 row affected (0.06 sec)

Next, check to make sure the database got created:

mysql> show databases;
+----------+
| Database |
+----------+
| mysql    |
| products |
| test     |
+----------+
3 rows in set (0.00 sec)

Yup, there it is. Now, let's set products as our database and then create a new table:

mysql> use products;
Database changed
mysql> show tables;
Empty set (0.00 sec)

No tables exist yet. Let's create one:

mysql> create table cables(
   -> name varchar(60),
   -> lengthInCm int(2),
   -> cableType ENUM( 'firewire', 'usb' ),
   -> cableID int(10) auto_increment primary key );
Query OK, 0 rows affected (0.15 sec)

Imagine a database set up for an e-commerce web site, designed to store info on all the site's products. The site sells firewire and usb cables of various lengths. The cables table will store info on the various cables sold by the site. Obviously, this is a very simple example. If this were a real database, we'd want to create multiple tables and have them reference each other. For example, we'd probably create a manufacturer table and have a field in the cables table refer to an entry in that table. This table is not very complicated and would not be terrifically useful in the real world, but it will serve to demonstrate the connection between PHP and MySQL. Read on...

Now let's populate the table:

mysql> insert into cables values ('Varco DX100', 100, 'firewire', 0);
Query OK, 1 row affected (0.13 sec)

Note that we embedded the manufacturer's name in the cable name field. Ick. As I mentioned, this should be a reference to a separate, manufacturer table. For now, this'll do.

Notice that we created an enumerated field. The cableType field can only take on one of two values, either 'firewire' or 'usb'.

We used a value of 0 for the cableID. This asks MySQL to create an index for this entry automatically.

Let's retrieve what we just put in:

mysql> select * from cables;
+------------- +------------+----------- + ------- +
| name         | lengthInCm | cableType  | cableID |
+------------- +------------+----------- + ------- +
| Varco DX100  | 100        | firewire   | 1       |
+------------- +------------+----------- + ------- +
1 row in set (0.04 sec)
Let's add a few more:
mysql> insert into cables values ('Genenco VT100', 100, 'firewire', 0);
Query OK, 1 row affected (0.38 sec)

mysql> insert into cables values ('Genenco VT50', 50, 'firewire', 0);
Query OK, 1 row affected (0.00 sec)

mysql> insert into cables values ('Genenco U100', 100, 'usb', 0);
Query OK, 1 row affected (0.00 sec)

mysql> insert into cables values ('Plexicor uShorty', 20, 'usb', 0);
Query OK, 1 row affected (0.00 sec)

mysql> insert into cables values ('Plexicor fShorty', 20, 'firewire', 0);
Query OK, 1 row affected (0.00 sec)
Now let's take a look at what we've got in the table:
mysql> select * from cables;
+ ------------------+------------ +---------- + --------- +
| name              | lengthInCm  | cableType | cableID   |
+ ------------------+------------ +---------- + --------- +
| Varco DX100       | 100         | firewire  |    1      |
| Genenco VT100     | 100         | firewire  |    2      |
| Genenco VT50      | 50          | firewire  |    3      |
| Genenco U100      | 100         | usb       |    4      |
| Plexicor uShorty  | 20          | usb       |    5      |
| Plexicor fShorty  | 20          | firewire  |    6      |
+ ------------------+------------ +---------- + --------- +
6 rows in set (0.39 sec)

Accessing Your Data from PHP

So now we have a database and a table filled with data. Our next step is to access this data and make it appear on a web page.

As a reminder, your PHP statements will be embedded within your html code. Once your .php file has been handed off to the PHP pre-processor, the pre-processor will interpret the PHP code and replace the code with the output generated by the code. If this confuses you, here's a very short example from last November's column, just to refresh your memory.

Using your plain-text text editor, create a new file called mysqltest.php and save it in your Sites folder, right alongside your test.php file we created earlier. Enter this code in the file and save:

<html>
   <head>
      <title>PHP Test</title>
   </head>
   <body>
      <p>This is some pure HTML loveliness.</p>
      <?php
         echo "<p>Hello, World!</p>\n";
      ?>
      <p>Did we echo properly?</p>
      <?php
         echo date("r");
         echo "\n";
      ?>
      <p>It works!!!</p>
   </body>
</html>

Once your file is saved, go into Safari and enter this address:

http://127.0.0.1/~davemark/mysqltest.php

Make sure you replace "davemark" with your own user name. Figure 2 shows what I saw when my page loaded. The first line was produced by the HTML. The second line was the result of the output of the PHP echo function. The echo function produced some HTML which was added to the stream. Next came another line of HTML ("Did we echo properly?"), followed by another pair of echos, echoing a date string and a return. This is all polished off by a last line of HTML, generating the string "It works!!!".


Figure 2. A simple PHP test.

If you view source on this output, here's what you get:

<html>
   <head>
      <title>PHP Test</title>
   </head>
   <body>
      <p>This is some pure HTML loveliness.</p>
      <p>Hello, World!</p>
      <p>Did we echo properly?</p>
      Wed, 15 Jun 2005 19:43:02 -0400
      <p>It works!!!</p>
   </body>
</html>

Go back and look at the original PHP. Make sure you understand how the original PHP got translated into this source. Remember, every chunk of PHP code in the original source was replaced by its output to achieve this HTML listing.

Connecting to the Database

OK, now we're ready to fetch our data. Our first step is to connect to our database. Open mysqltest.php and replace the contents with this code:

<html>
   <head>
      <title>MySQL Test</title>
   </head>
   <body>
      <p>Connecting to the database...</p>
      <?php
         $host = 'localhost';
         $user = 'root';
         $pw = '';
         $db = 'products';
	
         $link = mysql_connect( $host, $user, $pw )
            or die( 'Could not connect: ' . mysql_error() );
         echo 'Connected successfully';
         mysql_select_db( $db );
      ?>
      <p>If we got here, we've connected!</p>
   </body>
</html>

In the above code, replace the $user and $pw string values with whatever user and password you used to create the database. Save the code and reload this page in Safari: http://127.0.0.1/~davemark/mysqltest.php. Figure 3 shows my results.


Figure 3. Connecting to the database.

In a nutshell, we used the function mysql_connect() to connect to the database and the function mysql_select_db() to select the database. This is like logging in using the MySQL monitor, then saying use products.

One line of code worth taking a second look at is this one:

         $link = mysql_connect( $host, $user, $pw )
            or die( 'Could not connect: ' . mysql_error() );

Notice the use of "or" here. This is a pretty common technique in PHP. The second part of the or clause will only execute if the first part fails. The die() function is equivalent to exit(). die() will post the passed in string as output, then exit.

Notice the use of the "." operator to concatenate two strings together. This is another common PHP technique. In this case, the "." operator will build a single string from 'Could not connect: ' and the string returned by mysql_error(). mysql_error() returns the error message from the previous MySQL operation.

Our next step is to query the database and to print the data we retrieved.

Querying the Database

Back in your text editor, open the file mysqltest.php and replace its contents with this:

<html>
   <head>
      <title>MySQL Test</title>
   </head>
   <body>
      <p>Connecting to the database...</p>
      <?php
         $host = 'localhost';
         $user = 'root';
         $pw = '';
         $db = 'products';

         $link = mysql_connect( $host, $user, $pw )
            or die( 'Could not connect: ' . mysql_error() );
         echo 'Connected successfully';
         mysql_select_db( $db );
      ?>
      <p>Here's the table data:</p>
      <?php
         $sql_statement = "SELECT * FROM cables";
         $results = mysql_query( $sql_statement )
            or printf( "Query error: %s", mysql_error() );

         while ( $row = mysql_fetch_assoc( $results ) )
         {
            echo $row['cableID'] . ": ";
            echo "\"" . $row['name'] . "\"" . ", ";
            echo $row['lengthInCm'] . ", ";
            echo $row['cableType'];
            echo "<p>";
         }
			
         mysql_close( $link );
      ?>
   </body>
</html>

Save the file and reload it from Safari. Figure 4 shows my version of this run. Notice that the data is lightly formatted, with a colon (":") after the item number and commas between each of the fields.


Figure 4. Retrieving the data from the database.

Let's take a look at the code. We started with the original code, connecting to and selecting the database.

<html>
   <head>
      <title>MySQL Test</title>
   </head>
   <body>
      <p>Connecting to the database...</p>
      <?php
         $host = 'localhost';
         $user = 'root';
         $pw = '';
         $db = 'products';

         $link = mysql_connect( $host, $user, $pw )
            or die( 'Could not connect: ' . mysql_error() );
         echo 'Connected successfully';
         mysql_select_db( $db );
      ?>

Next, we spit out a line of HTML, preparing us for the table data to follow.

      <p>Here's the table data:</p>

We load our query into a PHP string, then pass the string into mysql_query(). This is the equivalent of typing the string into the MySQL monitor as a query. Once again, we use the "or" operator and this time, instead of exiting with die(), we'll display an error message using printf(). printf() is derived from its C forbearer, but is a part of the PHP library. As a point of interest, echo is not a function, but is a language construct. You can use echo as a statement, but can't pass it as a function. Use printf() instead.

<?php
         $sql_statement = "SELECT * FROM cables";
         $results = mysql_query( $sql_statement )
            or printf( "Query error: %s", mysql_error() );

Next, we enter a while loop, using mysql_fetch_assoc() to fetch one row of the table at a time. mysql_fetch_assoc() returns an associative array, which is an array indexed by name instead of by number. Instead of $row[3], you'd refer to $row['cableType']. Associative arrays are one of my favorite parts of PHP. Note that you could have also used mysql_fetch_row(), which would have returned a more tradition, numerically indexed array.

while ( $row = mysql_fetch_assoc( $results ) )
         {

For each row of data, we echo the field value, interspersed with colons, spaces and commas. Note that we also make frequent use of the "." operator.

            echo $row['cableID'] . ": ";
            echo "\"" . $row['name'] . "\"" . ", ";
            echo $row['lengthInCm'] . ", ";
            echo $row['cableType'];
            echo "<p>";
         }

Finally, we close the database using the value returned by mysql_connect(), then exit our PHP area and return to HTML.

mysql_close( $link );
      ?>
   </body>
</html>

Until Next Month...

Once again, seems we just get started when I've run out of room to write. <sigh>. Your assignment for this month is to first do a bit of research, then take the result of this month's query and build a nice HTML table instead of just dumping the data using echo. On the research side of things, go to http://php.net and dig down through the PHP manual, looking up the various functions we played with in this month's code. For example, here's a link to the page that talks about mysql_fetch_assoc():

http://php.net/manual/en/function.mysql-fetch-assoc.php

Take some time to get to know the PHP documentation. You'll find it chock full of examples and incredibly useful. Enjoy!


Dave Mark is a long-time Mac developer and author and has written a number of books on Macintosh development. Dave has been writing for MacTech since its birth! Be sure to check out the new Learn C on the Macintosh, Mac OS X Edition at http://www.spiderworks.com.

 
AAPL
$103.30
Apple Inc.
+0.80
MSFT
$45.09
Microsoft Corpora
-0.34
GOOG
$577.33
Google Inc.
+5.73

MacTech Search:
Community Search:

Software Updates via MacUpdate

TextSoap 7.4.0 - Flexible text editing u...
TextSoap is for people who work with text. TextSoap effortlessly cleans up text from endlessly different formats. Wash away unwanted characters, spaces, tabs. Fix paragraphs with hard returns at the... Read more
NetShade 6.0.2 - Browse privately using...
NetShade is an Internet security tool that conceals your IP address on the web. NetShade routes your Web connection through either a public anonymous proxy server, or one of NetShade's own dedicated... Read more
Mac DVDRipper Pro 5.0 - Copy, backup, an...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
pwSafe 3.1 - Secure password management...
pwSafe provides simple and secure password management across devices and computers. pwSafe uses iCloud to keep your password databases backed-up and synced between Macs and iOS devices. It is... Read more
StatsBar 1.8 - Monitor system processes...
StatsBar gives you a comprehensive and detailed analysis of the following areas of your Mac: CPU usage Memory usage Disk usage Network and bandwidth usage Battery power and health (MacBooks only)... Read more
Path Finder 6.5.5 - Powerful, award-winn...
Path Finder is a file browser that combines the familiar Finder interface with the powerful utilities and innovative features. Just a small selection of the Path Finder 6 feature set: Dual pane... Read more
QuarkXPress 10.2.1 - Desktop publishing...
With QuarkXPress, you can communicate in all the ways you need to -- and always look professional -- in print and digital media, all in a single tool. Features include: Easy to Use -- QuarkXPress is... Read more
Skype 6.19.0.450 - Voice-over-internet p...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more
VueScan 9.4.41 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Cloud 3.0.0 - File sharing from your men...
Cloud is simple file sharing for the Mac. Drag a file from your Mac to the CloudApp icon in the menubar and we take care of the rest. A link to the file will automatically be copied to your clipboard... Read more

Latest Forum Discussions

See All

Modern Combat 5 Gets a Major Multiplayer...
Modern Combat 5 Gets a Major Multiplayer Update Posted by Jessica Fisher on September 2nd, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Alien Creeps TD Review
Alien Creeps TD Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: EXPENSIVE DEFENSESUniversal App - Designed for iPhone and iPad Alien Creeps TD would be a fun if unremarkable Tower Defense game, but its heavy focus on... | Read more »
The Journey Down: Chapter Two Review
The Journey Down: Chapter Two Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: DARK YET ENTICINGUniversal App - Designed for iPhone and iPad It’s a little dark, in every sense of the word, but The Journey Down:... | Read more »
Function Space, a Social Network App for...
Function Space, a Social Network App for Science, Launches on iOS Posted by Ellis Spice on September 2nd, 2014 [ permalink ] | Read more »
Stupidfast – How Taylor Martinez Switche...
How do you make an Endless Running game more than just another Endless Running game? By adding real life prizes to it, of course! That’s the thinking behind StupidFast: a game designed for football enthusiasts, and the brainchild of former college... | Read more »
Little Raiders: Robin’s Revenge Review
Little Raiders: Robin’s Revenge Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: CASUAL RAIDINGUniversal App - Designed for iPhone and iPad Combining simple combat with village building is a potent combination for... | Read more »
Treasure Tombs: Ra Deal Coming from Bulk...
Treasure Tombs: Ra Deal Coming from Bulkypix and Dark Tonic This Fall Posted by Jessica Fisher on September 2nd, 2014 [ permalink ] Dark Tonic and | Read more »
Pirate Bash Review
Pirate Bash Review By Nadia Oxford on September 2nd, 2014 Our Rating: :: BAD PIRATES, GOOD TIMESUniversal App - Designed for iPhone and iPad Pirate Bash’s turn-based battles add an intriguing twist to a typical physics game.   | Read more »
Tiny Tower Vegas Review
Tiny Tower Vegas Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: STEADY DEVELOPMENTUniversal App - Designed for iPhone and iPad Build a huge tower again but Vegas-style in Tiny Tower Vegas.   | Read more »
The Manhattan Project Review
The Manhattan Project Review By Andrew Fisher on September 2nd, 2014 Our Rating: :: ROCKET SCIENCEUniversal App - Designed for iPhone and iPad The Manhattan Project offers a great Euro-style gameplay experience, but it is totally... | Read more »

Price Scanner via MacPrices.net

Apple refurbished iPads available for up to $...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more
Are We Now In The Post-Post-PC Era?
A longtime and thoroughgoing laptop aficionado, I was more than a little dismayed by Steve Jobs’s declaration back in 2010 when he sprang the iPad on an unsuspecting world. that we’d entered a “post-... Read more
PC Outlook Improves, But 2014 Shipments Still...
According to the International Data Corporation (IDC) Worldwide Quarterly PC Tracker, worldwide PC shipments are expected to fall by -3.7 percent in 2014. To hat’s actually an improvement from the... Read more
IDC Lowers Tablet Sales Projections for 2014...
Following a second consecutive quarter of softer than expected demand, International Data Corporation (IDC) has lowered its worldwide tablet plus 2-in-1 forecast for 2014 to 233.1 million units. The... Read more
Apple now offering refurbished 21-inch 1.4GHz...
The Apple Store is now offering Apple Certified Refurbished 21″ 1.4GHz iMacs for $929 including free shipping plus Apple’s standard one-year warranty. Their price is $170 off the cost of new models,... Read more
Save $50 on the 2.5GHz Mac mini, on sale for...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more
Save up to $300 on an iMac with Apple refurbi...
The Apple Store has Apple Certified Refurbished iMacs available for up to $300 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. These are the best prices on... Read more
The Rise of Phablets
Carlisle & Gallagher Consulting Group, a businesses and technology consulting firm focused solely on the financial services industry, has released an infographic depicting the convergence of... Read more
Bad Driver Database App Allows Good Drivers t...
Bad Driver Database 1.4 by Facile Group is a new iOS and Android app that lets users instantly input and see how many times a careless, reckless or just plain stupid driver has been added to the... Read more
Eddy – Cloud Music Player for iPhone/iPad Fre...
Ukraine based CapableBits announces the release of Eddy, its tiny, but smart and powerful cloud music player for iPhone and iPad that allows users to stream or download music directly from cloud... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.