Mysqli made simple

  1. Main problems of mysqli
  2. The saving grace
  3. The code
  4. Examples
  5. Comments

During recent years I spend a considerable effort telling the PHP community that PDO is much better choice than mysqli for a beginner.

But many people still prefer to use mysqli and there is a way to make it less painful than it usually is.

Main problems of mysqli

There are several problems with mysqli

The saving grace

Luckily, PHP greatly evolved these years, making most of the problems solved. Still we will need a simple wrapper function (but to be honest, we need such for PDO as well) but at least such a wrapper function / class would take a sane amount of code

The code

So here is the code:

function mysqli($mysqli$sql$params = [], $types "")
{
    if (!
$params) {
        return 
$mysqli->query($sql);
    }
    
$types $types ?: str_repeat("s"count($params));
    
$stmt $this->mysqli->prepare($sql);
    
$stmt->bind_param($types, ...$params);
    
$stmt->execute();
    return 
$stmt;
}

This function accepts four arguments. Two mandatory:

and two optional:

In a function, we are running the usual query() method if there are no parameters, and a prepared query otherwise.

For the prepared query, first we are defining the $types variable - it should be either a string supplied in the last parameter or a string consists of "s" symbols.
Then we are calling prepare() and then bind_param(), which is done in one simple call thanks to the argument unpacking operator.
Finally we executing the query and returning the statement. After that, we can get whatever information returned by query using the method chaining.

Examples

$start 0;
$limit 10;
$sql "SELECT * FROM users LIMIT ?,?";
$user_list mysqli($mysqli$sql, [$start$limit])->get_result->fetch_all();

As a result we will get an array that consists of all the rows returned by the query. Compare this tiny amount of code you usually writes!

Getting a single row is no less simpler:

$id 10;
$sql "SELECT * FROM users WHERE id=?";
$user_data mysqli($mysqli$sql, [$id])->get_result->fetch_assoc();

Insert and update queries are also very easy

$sql "INSERT INTO users SET username=?, password=?";
mysqli($mysqli$sql, [$username,$password]);

Now we have an associative array with user data!


Related articles: