mysqli
A connection to a MySQL database.
Syntax
new mysqli(?string $hostname = null, ?string $username = null, ?string $password = null, ?string $database = null, ?int $port = null)Parameters
| Parameter | Type | Description |
|---|---|---|
| $hostname | ?string | The server address. |
| $username | ?string | The user name. |
| $password | ?string | The password. |
| $database | ?string | The database name. |
| $port | ?int | Optional. The port. |
Return value
mysqliAn object with the `query()`, `prepare()`, `begin_transaction()` and `close()` methods.
Examples
Connecting and a prepared statement:
<?php
$db = new mysqli('127.0.0.1', 'root', '', 'shop');
$db->set_charset('utf8mb4');
$statement = $db->prepare('SELECT id, title FROM products WHERE price < ?');
$maxPrice = 500;
$statement->bind_param('i', $maxPrice);
$statement->execute();
foreach ($statement->get_result() as $row) {
echo $row['id'], ' ', $row['title'], "\n";
}Notes
The first argument of bind_param() lists the types: i for an integer, d for a float, s for a string. The extension works with MySQL only; PDO supports different databases with the same code.
See also
- PDO — A database connection.
- PDOStatement — A prepared statement and its result.
- password_hash — Creates a password hash for storing in a database.
Related recipes
In the tutorial
- MySQLi — Working with MySQL through the MySQLi extension — connecting, queries, prepared statements, the procedural style and a comparison with PDO.