MySQL Tutorial
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.
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases.
Both are object-oriented, but MySQLi also offers a procedural API.
Both support Prepared Statements. Prepared Statements protect from SQL injection.
The MySQLi extension is automatically installed in most cases, when php5 mysql package is installed.
For installation details, http://php.net/manual/en/mysqli.installation.php
Before we can access data in the MySQL database, we need to be able to connect to the server:
$conn = mysqli_connect("hostname", "username", "password", "database");
$conn = new mysqli("hostname", "username", "password", "database");
The MySQLi extension is automatically installed in most cases, when php5 mysql package is installed.
For installation details,http://php.net/manual/en/pdo.installation.php
$conn = new PDO("mysql:host=hostname;
dbname=database", "username", "password");
The connection to the MySQL database server will be closed automatically as soon as the execution of the script ends
To close the connection before, use the following:
//MySQLi Object-Oriented:
$conn->close();
//MySQLi Procedural:
mysqli_close($conn);
//PDO:
$conn = null;
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection MySQLi Object-Oriented
$conn = new mysqli($servername, $username, $password);
// Check connection MySQLi Object-Oriented
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Close Connection MySQLi Object-Oriented
$conn->close();
//----------------------------------------------------------
// Create connection MySQLi Procedural
$conn = mysqli_connect($servername, $username, $password);
// Check connection MySQLi Procedural
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
// Close Connection MySQLi Procedural
mysqli_close($conn);
//-----------------------------------------------------------
// Create connection PDO
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// Close Connection PDO
$conn = null;