PHP MySQLi
The MySQLi extension (MySQL Improved) is a relational database driver used in PHP to provide an interface with MySQL databases. It is the successor to the original mysql extension and offers several advantages:
- Object-oriented interface
- Procedural interface
- Support for prepared statements
- Support for transactions
- Enhanced debugging capabilities
MySQLi, along with PDO, is one of the two main ways to connect to a MySQL database in modern PHP.
Connecting to MySQL
You can connect to a MySQL database using either the object-oriented or the procedural style.
Object-Oriented Style
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Procedural Style
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Prepared Statements
Prepared statements are a crucial feature of MySQLi. They help prevent SQL injection attacks by separating the SQL query from the data.
<?php
// assuming $conn is the connection from the previous example
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
Fetching Data
You can fetch data from the database in several ways.
<?php
// assuming $conn is a valid connection
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
MySQLi vs. PDO
- Database Support: MySQLi only supports MySQL, whereas PDO supports many different databases (MySQL, PostgreSQL, SQLite, etc.).
- API: MySQLi offers both object-oriented and procedural APIs, while PDO only has an object-oriented API.
- Named Parameters: PDO supports named parameters (
:name) in prepared statements, which can make queries more readable. MySQLi only supports positional parameters (?).
For a new project, PDO is often recommended if you might ever need to switch to a different database. If you are certain that you will only ever use MySQL, MySQLi is a perfectly good choice.