Databases with PHP
Objectives
Connect to MySQL from PHP
Learn how to handle MySQL errors
Execute SQL statements with PHP
Use PHP to work with MySQL databases and tables Use PHP to manipulate database records
PHP and mySQL
2
PHP Overview
PHP has the ability to access and manipulate any database that is ODBC compliant
PHP includes functionality that allows you to work directly with different types of databases, without going through ODBC
PHP supports SQLite, database abstraction layer functions, and PEAR DB
PHP and mySQL
3
Enabling MySQL Support in
PHP
On UNIX/Linux systems:
Configure PHP to use the mysqli extension by specifying the --with-mysqli parameter when you run the configure command during installation On Windows:
PHP and mySQL
Copy the files libmysql.dll and php_mysqli.dll to the installation directory
Edit the php.ini configuration file and enable the extension=php_mysqli.dll directive
4
Opening and Closing a MySQL
Connection
Open a connection to a MySQL database server with the mysqli_connect() function
The mysqli_connect() function returns a positive integer if it connects to the database successfully or false if it does not
Assign the return value from the mysqli_connect() function to a variable that you can use to access the database in your script
PHP and mySQL
5
Opening and Closing a MySQL
Connection (continued)
The syntax for the mysqli_connect() function is:
$connection = mysqli_connect("host"[, "user ", "password",
"database"])
The host argument specifies the host name where your MySQL database server is installed
The user and password arguments specify a
MySQL account name and password
The database argument selects a database with which to work
PHP and mySQL
6
Opening and Closing a MySQL
Connection (continued)
Table 9-1 MySQL server information functions
PHP and mySQL
7
Opening and Closing a MySQL
Connection (continued)
Figure 9-1