PDO prepared statement with optional parameters

北城以北 提交于 2019-12-04 07:04:31

Some good old dynamic SQL query cobbling-together...

$sql = sprintf('SELECT * FROM user WHERE name LIKE :name %s %s',
               !empty($_GET['city'])   ? 'AND city   = :city'   : null,
               !empty($_GET['gender']) ? 'AND gender = :gender' : null);

...

if (!empty($_GET['city'])) {
    $stmt->bindParam(':city', '%'.$_GET['city'].'%', PDO::PARAM_STR);
}

...

You can probably express this nicer and wrap it in helper functions etc. etc, but this is the basic idea.

There is a nice little function which can help: tiniest query builder. No frameworks or ORMs needed to make code look like this:

public function updateUser(int $id, string $email = '', string $password = '', string $name = '') {
    $sql = \App\Utils\build_query([
        [               'UPDATE "users"'],
        [$email         ,'SET', 'email=:email'],
        [$password      ,',',   'password=:password'],
        [$name          ,',',   'name=:name'],
        [               'WHERE "id"=:id']
    ]);

    $stmt = $this->db->prepare($sql);
    $stmt->bindValue(':id', $id, \PDO::PARAM_INT);
    // Optional bindings.
    $email &&       $stmt->bindValue(':email', $email, \PDO::PARAM_STR);
    $password &&    $stmt->bindValue(':password', $password, \PDO::PARAM_STR);
    $name &&        $stmt->bindValue(':name', $name, \PDO::PARAM_STR);

    $stmt->execute();
}

Note how neatly query components are created, with support for optional ones of course. The && experssions by bindings simply check whether this parameter is given, and if it is, then appropriate bindValue are called.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!