Chapter 11. Using the mysqli Extension

Now that you understand how to access a MySQL database using PHP and the procedural mysql extensions, it’s time to learn how to do this with the improved mysqli extension. This is an object-oriented system, but there is a procedural version available if you prefer, and I’ll show you how to use both.

Querying a MySQL Database with mysqli

In this chapter, I replicate a number of the previous one’s examples, but rewrite them to use mysqli. This should serve as an excellent example of how you can bring any legacy code you encounter up-to-date.

Creating a Login File

Creating a login file is no different with mysqli than before, so it will look something like Example 11-1.

Example 11-1. The login.php file
<?php // login.php
  $db_hostname = 'localhost';
  $db_database = 'publications';
  $db_username = 'username';
  $db_password = 'password';
?>

As in the previous chapter, the database we’ll be using is the one called publications, and the variables $db_username and $db_password should be set to the username and password that you have been using with MySQL.

Connecting to MySQL

With the login.php file saved, you access the database with the require_once statement, and connect to the server in the manner shown in Example 11-2.

Example 11-2. Connecting to a MySQL server with mysqli
<?php
  require_once 'login.php';
  $connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);

  if ($connection->connect_error) die($connection->connect_error)
?>

This example ...

Get Learning PHP, MySQL, JavaScript, CSS & HTML5, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.