Databases with PHP
| Introduction | |
| Ways to work with databases in PHP | |
| mysqli | |
| mysqli OOP example | |
| mysqli procedural example | |
| PDO |
Introduction
More on relational databases in the articles:
Ways to work with databases in PHP
-
PDO
- one API for different databases
- With extra libraries, e.g. Doctrine ORM
mysqli
MySQLi is a driver for MySQL databases. Used instead of deprecated mysql since PHP 5.
i stands for improved
Examples of connecting to a database with mysqli
OOP
<$php
$servername = "localhost";
$username = "andrei";
$password = "secret";
// Open a MySQL connection
$conn = new mysqli($servername, $username, $password);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Succesfully connected to MySQL!";
// Create a database
$sql = "CREATE DATABASE newDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully!";
} else {
echo "Error creating database: " . $conn->error;
}
?>
Procedural
<$php
$srvname = "localhost";
$usrname = "andrei";
$password = "secret";
// Open a MySQL connection
$conn = mysqli_connect($srvname, $usrname, $password);
// Check the connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Succesfully connected to MySQL!";
?>
PDO
PHP Data Objects. Supports 12+ different databases.
If your project may switch relational databases - using PDO makes sense.
Example of creating a table
CREATE TABLE `sample`.`Person` (
`Id` INT NOT NULL AUTO_INCREMENT ,
`Firstname` VARCHAR(50) NOT NULL ,
`Lastname` VARCHAR(50) NOT NULL ,
`email` VARCHAR(255) NOT NULL ,
PRIMARY KEY (`Id`)
)
ENGINE = InnoDB;
Article author: Andrei Olegovich