This repository has been archived on 2020-02-18. You can view files and clone it, but cannot push or open issues or pull requests.
ical-drupal-calendar/includes/MysqlConnector.php

119 lines
3.3 KiB
PHP

<?php
namespace Pandy06269\iCalDrupal\includes;
class MysqlConnector
{
protected $config;
/**
* @var \mysqli
*/
protected $connection;
public function close()
{
if (!is_null($this->connection) && $this->connection->ping())
{
$this->connection->close();
}
}
public function open()
{
if (defined('DEBUG') && DEBUG)
{
echo sprintf('Connecting to Drupal database called "%s" on "%s:%d"' . PHP_EOL, $this->config['database'], $this->config['host'], $this->config['port']);
}
$this->connection = new \mysqli(
$this->config['host'],
$this->config['username'],
$this->config['password'],
$this->config['database'],
$this->config['port']
);
if ($this->connection->connect_errno)
{
throw new \Exception(sprintf('Error connecting to database: %s', $this->connection->connect_error));
}
}
protected function executeQuery($sql, array $paramTypes = [], array $paramValues = [])
{
$statement = $this->prepareQueryStatement($sql, $paramTypes, $paramValues);
$returnCode = $statement->execute();
if ($returnCode === false)
{
throw new \Exception(sprintf('Failed executing the query: %s', $this->connection->error));
}
}
protected function executeQueryResult($sql, array $paramTypes = [], array $paramValues = [])
{
$statement = $this->prepareQueryStatement($sql, $paramTypes, $paramValues);
$returnCode = $statement->execute();
if ($returnCode === false)
{
throw new \Exception(sprintf('Failed executing the query: %s', $this->connection->error));
}
$results = [];
$result = $statement->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$results[] = $row;
}
return $results;
}
protected function getLastInsertedID()
{
$result = $this->executeQueryResult('SELECT LAST_INSERT_ID() AS id');
if (count($result) > 0)
{
return intval($result[0]['id']);
}
return -1;
}
private function prepareQueryStatement($sql, array $paramTypes = [], array $paramValues = [])
{
$statement = $this->connection->prepare($sql);
if ($statement === false)
{
throw new \Exception(sprintf('Failed preparing the query: %s', $this->connection->error));
}
if (count($paramTypes) > 0 && count($paramValues) > 0)
{
$a_params = array();
$param_type = '';
$n = count($paramTypes);
for ($i = 0; $i < $n; $i++)
{
$param_type .= $paramTypes[$i];
}
/* with call_user_func_array, array params must be passed by reference */
$a_params[] = &$param_type;
for ($i = 0; $i < $n; $i++)
{
/* with call_user_func_array, array params must be passed by reference */
$a_params[] = &$paramValues[$i];
}
/* Prepare statement */
call_user_func_array(array($statement, 'bind_param'), $a_params);
}
return $statement;
}
}