O'Reilly logo

Programming PHP, 3rd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

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

MySQLi Object Interface

The most popular database platform used with PHP is the MySQL database. If you look at the MySQL website (www.mysql.com/) you will discover that there are a few different versions of MySQL you can use. We will look at the freely distributable version known as the community server. PHP has a number of different interfaces to this database tool as well, so we will look at the object-oriented interface known as MySQLi, a.k.a. the MySQL Improved extension. If you are not overly familiar with OOP interfaces and concepts, be sure to review Chapter 6 before you get too deeply into this section.

Since this object-oriented interface is built into PHP with a standard installation configuration (you just have to activate the MySQLi extension in your PHP environment), all you have to do to start using it is instantiate its class, as in the following code:

$db = new mysqli(host, user, password, databaseName);

In this example, we have a database named library, and we will use the fictitious username of petermac and the password of 1q2w3e9i8u7y. The actual code that would be used is:

$db = new mysqli("localhost", "petermac", "1q2w3e9i8u7y", "library");

This gives us access to the database engine itself within the PHP code; we will specifically access tables and other data later. Once this class is instantiated into the variable $db, we can use methods on that object to do our database work.

A brief example of generating some code to insert a new book into the library database ...

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