Chapter 5. Connecting PHP to MySQL

Now that you’ve seen a bit of the power of PHP and MySQL, it’s time to bring these two juggernauts together. With many programming languages, any time you want to interact with a database, you have to download and install extra code or small plug-ins. PHP isn’t like that, though; it comes ready to connect to MySQL from the moment you run the php command.

Even though you’ve only recently begun your journey to PHP mastery, you’re ready to use a database from within your scripts. You’ll just need to learn a few new commands and how to deal with the problems that can come up when you’re working with a database. In fact, you’re going to build a simple form with which you can enter SQL and run it against your MySQL database. Who needs the mysql command-line tool when you’re a PHP programmer?

Then, to put a cherry on top of your towering sundae of PHP and MySQL goodness, you’ll write another script. This one takes all the information from the forms you’ve already been building, adds that information into a database, and then adds one more form to with which your users can search for another user by name. All that in one chapter? Yes indeed.

Writing a Simple PHP Connection Script

No matter how simple or advanced your PHP scripts, if they communicate with a database, they’ll begin with the same few steps:

  1. Connect to a MySQL installation.

  2. USE the correct MySQL database.

  3. Send SQL to the database.

  4. Get the results back.

  5. Do something with the results.

Depending on the ...

Get PHP & MySQL: The Missing Manual, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.