I'm new to web programming, and writing some web apis to enable users to sync their data between devices.
Is it okay to use singleton pattern to prevent reconnecting the MySQL database on every api call?
<?php
final class MySQLiConnection
{
private static $connection = null;
private function __construct() {}
public static function getInstance() : MySQLiConnection
{
if ($connection == null || !$connection->ping())
{
$connection = new mysqli("localhost", "id", "password", "database");
}
return $connection;
}
public function execute(string $sql, iterable $params) : void
{
if ($statement = $connection->prepare($sql))
{
foreach ($params in $param)
{
if (is_int($param))
{
$statement->bind_param("i", $param);
}
else if (is_double($param))
{
$statement->bind_param("d", $param);
}
else if (is_string($param))
{
$statement->bind_param("s", $param);
}
}
$statement->execute();
$statement->close();
}
}
public function getResult(string $sql, iterable $params) : mysqli_result
{
if ($statement = $connection->prepare($sql))
{
foreach ($params in $param)
{
if (is_int($param))
{
$statement->bind_param("i", $param);
}
else if (is_double($param))
{
$statement->bind_param("d", $param);
}
else if (is_string($param))
{
$statement->bind_param("s", $param);
}
}
$statement->execute();
$result = $statement->get_result();
$statement->close();
return $result;
}
}
}
// example
MySQLiConnection::getInstance()->execute("SELECT * FROM users WHERE forename = ? AND surname = ?", "ben", "dover");
?>