Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to connect to MySQL with MySQLi

Short answer

Create a mysqli object and set the charset:

<?php
 
$db = new mysqli('127.0.0.1', 'shop_user', getenv('DB_PASSWORD'), 'shop');
$db->set_charset('utf8mb4');
 
$result = $db->query('SELECT id, title FROM products LIMIT 10');
 
foreach ($result as $row) {
    echo $row['id'], ' ', $row['title'], "\n";
}

A query with parameters

Values from a user are passed through a prepared statement:

<?php
 
$db = new mysqli('127.0.0.1', 'shop_user', getenv('DB_PASSWORD'), 'shop');
 
$statement = $db->prepare('SELECT title FROM products WHERE price < ? AND title LIKE ?');
$statement->execute([500, '%tea%']);
 
foreach ($statement->get_result() as $row) {
    echo $row['title'], "\n";
}

Errors

Since PHP 8.1 MySQLi throws a mysqli_sql_exception on an error — there is no need to check the result of every call by hand.

Functions used in this recipe

  • mysqli — A connection to a MySQL database.
  • PDO — A database connection.
  • getenv — Returns the value of an environment variable.

Thanks for reading!

Donate to the site — we work hard for you.