You are on page 1of 22

Connecting PHP to MYSQL

Connecting PHP to MYSQL

▪ PHP 5 and later can work with a MySQL database using:


– MySQLi extension (the "i" stands for improved)
– PDO (PHP Data Objects)
MySQL Examples in Both MySQLi and PDO
Syntax

▪ In this, and in the following chapters we demonstrate three ways of


working with PHP and MySQL:
– MySQLi (object-oriented)
– MySQLi (procedural)
– PDO
Open a Connection to MySQL

▪ Before we can access data in the MySQL database, we need to be able


to connect to the server
Example (MySQLi Object-Oriented)
Example (MySQLi Procedural)
Example (PDO)
Close the Connection

▪ The connection will be closed automatically when the script ends. To


close the connection before, use the following:
▪ MySQLi Object-Oriented:
– $conn->close();

▪ MySQLi Procedural:
– mysqli_close($conn);

▪ PDO:
– $conn = null;
Exceptions, a Review
(or not?)
What Is an Exception?

▪ An exception is an event, which occurs during the execution of a


program, that disrupts the normal flow of the program's instructions.
▪ When an error occurs within a method, the method creates an object
and hands it off to the runtime system.
▪ Exception object – contains information about the error, including its
type and the state of the program when the error occurred. Creating an
exception object and handing it to the runtime system is called
throwing an exception.
What Is an Exception?

▪ After a method throws an exception, the runtime system attempts to


find something to handle it.
Catching and Handling
Exceptions in PHP
Catching and Handling Exceptions in PHP

▪ An exception can be thrown and caught.


▪ Code may be surrounded in a try block, to facilitate the catching of
potential exceptions. Each try must have at least one corresponding
catch or finally block.
The try-catch
The try-catch-finally
The try-catch-finally
Creating Databases,
Tables, and Inserting
data using PHP
Create a MySQL Database Using PDO
Create a MySQL Table Using PDO

▪ The CREATE TABLE statement is used to create a table in MySQL.


▪ We will create a table named "MyGuests", with five columns: "id",
"firstname", "lastname", "email" and "reg_date":
Create a MySQL Table Using PDO
Insert MYSQL Data Using PDO

▪ Here are some syntax rules to follow:


– The SQL query must be quoted in PHP
– String values inside the SQL query must be quoted
– Numeric values must not be quoted
– The word NULL must not be quoted

▪ The INSERT INTO statement is used to add new records to a MySQL


table:
Insert MYSQL Data Using PDO

You might also like