<?php
function assoc($sql, $array = [])
{
global $pdo;
$sql = $pdo->prepare($sql);
foreach ($array as $key => $value) {
if (is_bool($value)) {
$type = PDO::PARAM_BOOL;
} elseif (is_null($value)) {
$type = PDO::PARAM_NULL;
} elseif (is_int($value)) {
$type = PDO::PARAM_INT;
} elseif (is_string($value)) {
$type = PDO::PARAM_STR;
} else {
$type = false;
}
$sql->bindValue($key, $value, $type);
}
$sql->execute();
return $sql->fetch();
}
<?php
class MyPDO
{
protected const DB_HOST = 'localhost';
protected const DB_NAME = 'test';
protected const DB_USER = 'root';
protected const DB_PASS = '';
protected const DB_CHAR = 'utf8';
public static function connect()
{
$opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => true];
$dsn = 'mysql:host=' . self::DB_HOST . ';dbname=' . self::DB_NAME . ';charset=' . self::DB_CHAR;
return new PDO($dsn, self::DB_USER, self::DB_PASS, $opt);
}
public static function run($sql, $params = [])
{
$query = self::connect()->prepare($sql);
if (empty($params[0])) {
foreach ($params as $key => $value) {
if (is_bool($value)) {
$type = PDO::PARAM_BOOL;
} elseif (is_null($value)) {
$type = PDO::PARAM_NULL;
} elseif (is_int($value)) {
$type = PDO::PARAM_INT;
} elseif (is_string($value)) {
$type = PDO::PARAM_STR;
} else {
$type = false;
}
$query->bindValue($key, $value, $type);
}
} else {
$i = 1;
foreach ($params as $value) {
if (is_bool($value)) {
$type = PDO::PARAM_BOOL;
} elseif (is_null($value)) {
$type = PDO::PARAM_NULL;
} elseif (is_int($value)) {
$type = PDO::PARAM_INT;
} elseif (is_string($value)) {
$type = PDO::PARAM_STR;
} else {
$type = false;
}
$query->bindValue($i, $value, $type);
$i++;
}
}
$query->execute();
return $query;
}
}