O'Reilly logo

MySQL in a Nutshell by Russell J.T. Dyer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 13. PHP API

One of the most popular programming language and database engine combinations for the Web is PHP with MySQL. This combination works well for many reasons: primarily the speed, stability, and simplicity of both applications. The first part of this chapter provides a basic tutorial on how to connect to MySQL and how to query MySQL with PHP. Following the tutorial is a reference of PHP MySQL functions in alphabetical order. For the examples in this chapter, a database for a fictitious computer support business is used. The database contains one table with client work requests (workreq) and another with client contact information (clients).

Using PHP with MySQL

This section presents the basic tasks you need to query a MySQL database from PHP.

Connecting to MySQL

For a PHP script to interface to MySQL, first you must make a connection to it, thus establishing a MySQL session. To connect to the workrequests database, a PHP script might begin like so:

<?php
   
$host = 'localhost';
$user = 'russell';
$pw = 'dyer';
$db = 'workrequests';
   
mysql_connect($host, $user, $pw)
   or die(mysql_error);
mysql_select_db($db);
   
?>

This section of PHP code starts by establishing the variables with information necessary for connecting to MySQL and the database. After that, PHP connects to MySQL by giving the host and user variables. If it's unsuccessful, the script dies with an error message. If the connection is successful, though, the workrequests database is selected for use. Each PHP script ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required