I'm creating some web apis to sync some data between desktop/mobile apps.
Working on it, I wrote a simple wrapper for mysqli connection to simplify querying like:
// examples
$connection = new MySQLiConnection();
$connection->execute("INSERT INTO songs VALUES ('God\'s Plan', 'Drake')");
$connection->execute('INSERT INTO songs VALUES (?, ?)', 'Perfect', 'Ed Sheeran');
$result = $connection->getResult('SELECT * FROM songs');
var_dump($result);
$result = $connection->getResult('SELECT * FROM songs WHERE artist = ?', 'Ed Sheeran');
var_dump($result);
Code of the wrapper:
<?php
final class MySQLiConnection
{
private $connection;
public function __construct()
{
$this->connection = new mysqli('localhost', 'id', 'password', 'database');
if ($this->connection->connect_errno)
{
throw new mysqli_sql_exception('Failed to open mysqli connection: ' . $this->connection->connect_error);
}
if (!$this->connection->set_charset('utf8'))
{
throw new mysqli_sql_exception('Failed to set utf8 character set: ' . $this->connection->error);
}
}
public function __destruct()
{
if (!$this->connection->close())
{
throw new mysqli_sql_exception('Failed to close mysqli connection: ' . $this->connection->error);
}
}
private function buildStatement(string $sql, ...$params) : mysqli_stmt
{
if ($statement = $this->connection->prepare($sql))
{
if (!empty($params))
{
$types = '';
foreach ($params as $param)
{
if (is_int($param))
{
$types .= 'i';
}
elseif (is_float($param))
{
$types .= 'd';
}
elseif (is_string($param))
{
$types .= 's';
}
else
{
$types .= 'b';
}
}
$statement->bind_param($types, ...$params);
}
return $statement;
}
throw new mysqli_sql_exception('Failed to prepare mysqli_stmt: ' . $this->connection->error);
}
public function execute(string $sql, ...$params) : void
{
$statement = $this->buildStatement($sql, ...$params);
$success = $statement->execute();
$statement->close();
if (!$success)
{
throw new mysqli_sql_exception('Failed to execute mysqli_stmt: ' . $this->connection->error);
}
}
public function getResult(string $sql, ...$params) : mysqli_result
{
$statement = $this->buildStatement($sql, ...$params);
$success = $statement->execute();
if ($success)
{
$result = $statement->get_result();
$statement->close();
return $result;
}
$statement->close();
throw new mysqli_sql_exception('Failed to execute mysqli_stmt: ' . $this->connection->error);
}
}
?>