In this lesson our instructor talks about using PHP from MySQL. First, he discusses PHP and MySQL architecture. Then he talks about MySQLi extension, steps to using MySQL from PHP, and connecting to a database. He also lectures on running an SQL statement, processing the results, and closing the connection. He ends the lesson with nine homework challenges.
PHP provides a built-in extension called Mysqli for interacting with MySQL databases from PHP code.
The extension is enabled in 'php.ini' via the line:
There are essentially four steps required in PHP to execute an SQL statement on a MySQL server from a PHP
Connect to MySQL database
Run SQL statement
Process statement results
Close connection to database
To connect to a MySQL database, you create an instance of a MySQLi object using its constructor
that takes arguments for the hostname, username, password, & database name for the MySQL database you are
To test for connection errors, the MySQLi object properties conn_errno or
conn_error can be tested.
A SQL statement can be run on a database using the MySQLi->query() object method that takes a
SQL query string as its argument. For successful queries, it will TRUE for non-SELECT
queries or a MySQLi_Result object for SELECT queries. FALSE is returned if a
The MySQLi object property affected_rows can be checked to get the number of rows
affected by a query.
For INSERT statements on tables with an AUTO_INCREMENT column, the
MySQLi object property insert_id can be accessed to retrieve the ID auto-generated for an
The MySQLi->close() object method is used to close the object’s connection to the MySQL
database. It will return TRUE if the connection was successfully closed and FALSE
Note: any access to affected_rows & insert_id must be made before
close() is called
Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.