The 'mysqli' extension in PHP stands for "MySQL Improved". This is an advanced version of PHP's original MySQL extension, which provides an efficient and convenient interface to the MySQL database. It is designed to work with MySQL version 4.1.13 or newer, offering various benefits over the older mysql extension such as prepared statements, multiple statements, transactions, and more.
Here is a simple example to illustrate:
$stmt = $mysqli->prepare("INSERT INTO Products (ProductName, Price) VALUES (?, ?)");
$stmt->bind_param("si", $product_name, $price);
$product_name = "Apple";
$price = 1;
$stmt->execute();
$product_name = "Orange";
$price = 2;
$stmt->execute();
mysqli
allows the execution of multiple SQL statements with one call to mysqli::multi_query
. It can significantly increase the performance when executing many queries.$query = "SELECT count(*) FROM Products;";
$query .= "INSERT INTO Products(ProductName, Price) VALUES ('Banana', 3)";
if ($mysqli->multi_query($query)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
} while ($mysqli->next_result());
}
When using the mysqli extension, it's important to always check for successful connection to the database. This can be done using the mysqli_connect_error
function, which will return a string description of the last connect error.
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
Another good practice involves using the real escape string function (mysqli_real_escape_string
) for all variables included in SQL queries. This helps to prevent SQL injection attacks by escaping any special characters in a string.
Remember, despite the significant improvements brought by the 'mysqli' extension, it's also recommended to consider other options like PDO (PHP Data Objects) depending on your specific project needs and circumstances. It is crucial to select the appropriate tool that aligns with your project structure, database type, and overall requirements.