MySQLi dynamic prepared function with array binding

二次信任 提交于 2019-11-29 12:27:00

though to implement named parameters would be quite a task, the rest is pretty doable.

A PHP >= 5.6 variant, implementing splat operator:

function query($query, $params = NULL, $types = NULL)
{
    if (!$params)
    {
        return $mysqli->query($query);
    }
    $statement = $this->mysqli->prepare($select);
    $types = $types ?: str_repeat('s', count($params));
    $statement->bind_param($types, ...$params);
    $statement->execute();
    return $statement->get_result();
}

used like this

$sql = "SELECT * FROM accounts WHERE email = ? AND id = ?";
$row = $engine->query($sql, [$_POST['mail'], 2])->fetch_assoc();

or, if you want to set types explicitly

$row = $engine->query($sql, [$_POST['mail'], 2], "si")->fetch_assoc();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!