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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.