Lesson 20

Creating and Connecting to the Database

In this lesson, you learn the interfaces that PHP has to communicate with a MySQL database. The original method was with an extension to PHP called mysql. You can still find this in older code, but it has been replaced by the mysqli extension for PHP 5. Mysqli is an improved, more secure version that takes advantage of features added to newer versions of MySQL. It is recommended for new work.

PDO (PHP Data Objects) is an extension to PHP for connecting to various databases, not just MySQL. The same PHP code enables you to connect to MySQL, PostreSQL, and SQLite databases, among others. You use different drivers to switch from one database type to the other.

Connecting with MySQL/Mysqli

Mysql was the traditional way to communicate with MySQL. When mysqli came along in PHP 5, it added the following features:

  • Object-oriented interface: Mysqli has the mysqli class, the mysql_stmt class for queries, and the mysqli_result class for results. Each of these has properties that give you information on the connection, the request you are making, or the data you have retrieved. They also have methods that enable you to perform actions. There is still a procedural interface similar to mysql if you prefer to use that.
  • Support for prepared statements: With prepared statements you set up the request once and then send the particulars for the actual request. Reusing the same type of requests works faster than creating a new request each time. ...

Get PHP and MySQL® 24-Hour Trainer now with the O’Reilly learning platform.

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