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)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn-\gtconnect_error);
}
echo "Connected successfully";
?\gt
**Example (MySQLi Procedural)**
\lt?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?\gt
**Example (PDO)**
\lt?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn-\gtsetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e-\gtgetMessage();
}
?\gt
**Close the Connection**
The connection will be closed automatically when the script ends. To close the connection before, use the following:
**Example (MySQLi Object-Oriented)**
$conn->close();
Example (MySQLi Procedural)
mysqli_close($conn);
**Example (PDO)**
$conn = null;