← Previous
Next →
Create object:
← Previous
Next →
In this tutorial, we will learn how to connect PHP to a MySQL database.
In order to store or access the data inside a MySQL database, you first need to connect to the MySQL database server. PHP offers two different ways to connect to MySQL server: MySQLi (Improved MySQL) and PDO (PHP Data Objects) extensions.
Three Ways to Connecting to MySQL Database Server
First, you need to create a database in MySQL server:
create database test_db
1. Connect to MySQLi using Procedural way
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$host= "localhost";
$username= "root";
$password = "";
$db_name = "test_db";
// MySQLi, Procedural way
$mysql_connection = mysqli_connect($host, $username, $password, $db_name);
// Check connection
if($mysql_connection === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($mysql_connection);
// Close connection
mysqli_close($link);
?>
2. Connect to MySQLi using Object Oriented way
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$host= "localhost";
$username= "root";
$password = "";
$db_name = "test_db";
// MySQLi, Object Oriented way
$mysql_connection = new mysqli($host, $username, $password, $db_name);
// Check connection
if($mysql_connection === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($mysql_connection);
// Close connection
$mysql_connection->close();
?>
Note that we have created object:
// MySQLi, Object Oriented way
$mysql_connection = new mysqli($host, $username, $password, $db_name);
Close connection:
// Close connection
$mysql_connection->close();
3. Connect to MySQLi using PHP Data Objects (PDO) way
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
$pdo = new PDO("mysql:host=localhost", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Print host information
echo "Connect Successfully. Host info: " .
$pdo->getAttribute(constant("PDO::ATTR_CONNECTION_STATUS"));
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
?>
// Close connection
unset($pdo);
$pdo = new PDO("mysql:host=localhost", "root", "");
Close connection:
// Close connection
unset($pdo);
Comments
Post a Comment