O'Reilly logo

Learning PHP, MySQL, JavaScript, CSS & HTML5, 3rd Edition by Robin Nixon

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 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 ...

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