How to connect properly using mysqli

  1. Object syntax
  2. Credentials explained
  3. Functions explained
  4. Procedural syntax
  5. Handling connection errors
  6. Accessing the newly created connection
  7. Making prepared queries less verbose
  8. Storing database credentials
  9. Include files
  10. Comments (6)

Having answered thousands questions on Stack Overflow, I was able to determine the most common problems PHP developers stuck into when working with mysqli. So I decided to write this tutorial emphasizing on the following matters:

Object syntax

$host '127.0.0.1';
$port 3306;
$dbname 'test';
$user 'root';
$pass '';
$charset 'utf8mb4';

mysqli_report(MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT);
try {
    
$db = new mysqli($host$user$pass$dbname$port);
    
$db->set_charset($charset);
    
$db->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE1);
} catch (
\mysqli_sql_exception $e) {
     throw new 
\mysqli_sql_exception($e->getMessage(), $e->getCode());
}
unset(
$host$dbname$user$pass$charset$port); // we don't need them anymore

Credentials explained

First of all we are defining variables that contain connection credentials. This set is familiar to anyone who were using the old mysql_connect() function, save for $charset may be, which was rarely used (although it should have been).

Functions explained

Beside new mysqli() we are using two additional functions here:

Procedural syntax

Previously here was an example for the procedural mysqli syntax. But some time ago I decided to remove it for the following reasons:

Just adapt the object syntax, it will take you just two minutes, but your code will start looking much cooler immediately!

Handling connection errors

An uncaught exception is converted to a PHP fatal error. It is not a problem by itself, errors are for the good. A programmer desperately needs an error message to get the idea on what's going on when something goes wrong. But such a converted error contains a stack trace added to the error message, which in case of mysqli connection error would include the constructor parameters, which happen to be the database credentials. Again, it shouldn't be a problem, as on a live site displaying errors should be always turned off anyway, but we are humans and we make mistakes. So, to avoid even a slight chance to reveal the credentials, we are catching the Exception and immediately throwing a brand new one with the same error message but without erasing the stack trace. Usually it's a bad move but in this case it's considered a good trade-off between security and convenience.

Just keep in mind that if your connection code is wrapped in a function, this function's parameters will be shown in the stack trace in turn. So, to avoid the credentials leak in this place, either send the credentials into this function in the form of an array or an object, or fetch them inside the function.

Accessing the newly created connection

There is one thing that makes mysqli a bit more complex to use than old mysql_connect related stuff. Although one was able to call mysql_query() anywhere in the code, without taking care of the connection, which was magically supplied by PHP, with mysqli one should always make sure that once created mysqli instance is available in each part of their script. In a nutshell, it's all about accessing a $db variable inside functions and object's methods.

So, to use mysqli in the global scope, just create a PHP file with the code above, and then include it in the every PHP script that needs a database connection. Whereas to access it in the functions/methods simply pass it as a parameter:

function getUserData($db$id) {
    
$stmt $db->prepare("SELECT * FROM user WHERE id=?");
    
$stmt->bind_param("s"$id);
    
$stmt->execute();
    return 
$stmt->get_result()->fetch_assoc();
}

remember that if a function is called inside another function, this outer function should take the $db variable as a parameter as well.

In case your code is OOP, you most likely would put it in the constructor of your own database wrapper class. In this case you may want to check whether your class has any of the common mistakes, just in case.

Making prepared queries less verbose

Given a rather verbose syntax of mysqli prepared statements (and the fact you must always use them if variables are going to be used in the query), it would be quite useful to have a helper function, as described in the corresponding article.

Now you can tell the difference:

$stmt $db->prepare("SELECT * FROM user WHERE id=?");
$stmt->bind_param("s"$id);
$stmt->execute();
$user $stmt->get_result()->fetch_assoc();

vs.

$user prepared_select($db"SELECT * FROM user WHERE id=?", [$id])->fetch_assoc();

Hence it would be very hand to add such an extension to our database class.

Storing database credentials

Having credentials hardcoded in the same file quickly proves inconvenient. When the site goes live, it would need different credentials for sure, hence you would have to rewrite this file. And when you will need to work a bit more on the code, you will have to rewrite it back... and so on. Which is far from being convenient.

There are many advanced techniques for providing the settings but the simplest one would be just storing them in a separate file. This way you'll be able to keep different configuration files on different servers. So instead of hardcoding the credentials, just use variables defined in a separate file:

<?php
$host 
'127.0.0.1';
$port 3306;
$db   'test';
$user 'root';
$pass '';
$charset 'utf8mb4';

and then just include this file in your database connection script

Include files

To sum everything up, let's create two files, one named mysqli.php with the following code inside,

<?php

mysqli_report
(MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT);
require 
__DIR__.'/db_credentials.php';
$db = new mysqli($host$user$pass$db$port);
$db->set_charset($charset);
$db->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE1);
unset(
$host$db$user$pass$charset);

function 
prepared_query($db$sql$params$types "")
{
    
$types $types ?: str_repeat("s"count($params));
    
$stmt $db->prepare($sql);
    
$stmt->bind_param($types, ...$params);
    
$stmt->execute();
    return 
$stmt;
}

function 
mysqli_info_array($mysqli) {
    
$pattern '~Rows matched: (?<matched>\d+)  Changed: (?<changed>\d+)  Warnings: (?<warnings>\d+)~';
    
preg_match($pattern$mysqli->info$matches);
    return 
array_filter($matches"is_string"ARRAY_FILTER_USE_KEY);
}

and also in the same directory a file called db_credentials.php where the credentials should go.


Related articles: