CS214-Lect-PHP and MySQL Connections
CS214-Lect-PHP and MySQL Connections
• PHP and MySQL interact with each other through PHP and
MySQL extensions.
• We connect to MySQL from PHP using PHP’s MySQL-related
extensions.
• There are two types of such extensions for PHP 5.5.0 and
higher or later versions since 2012, MySQLi ("i" stands from
"improved") and PDO (PHP Data Objects).
• Now, the question is "Which Should I Use? MySQLi or PDO?".
• You are free to use "whatever you like".
• I will be using MySQLi, however you may use PDO when
"multiple database support“ is needed since PDO offers
support for many databases (not only MySQL).
Wednesday, June 25, 2025 Lecturer : Zano C
MySQL Database creation
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
// Create connection
$conn = new mysqli($servername, $username, $password,Sdbase);
// Check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
} else {
echo “connection established “;
}
$conn->close();
?>
Wednesday, June 25, 2025 Lecturer : Zano C
Connecting to the MySQL Database
•
// Create connection
$conn = new mysqli($servername, $username,
$password,Sdbase);
// Check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn-
>connect_error, E_USER_ERROR);
} else {
echo “connection established “;
}
$conn->close();
?>
Wednesday, June 25, 2025 Lecturer : Zano C
Connecting to the MySQL Database
// Create connection
$conn = new mysqli($servername, $username, $password,Sdbase);
// Check connection
if (mysqli_connect_errno()) {
trigger_error('Database connection failed: ' . mysqli_connect_error(), E_USER_ERROR);
} else {
echo “connection established “;
}
mysqli_close($conn);
?>
Wednesday, June 25, 2025 Lecturer : Zano C