且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP/PDO-使用变量赋值作为获取语句

更新时间:2023-02-26 10:55:00

此功能太可怕了.仅此一个参数的长尾巴!而且缺乏准备好的陈述.还有一个与数据库相关的功能,它可以自行决定是否输出错误,好像数据库交互与其他代码有所不同.

This function is horrible. That long tail of parameters alone! And the lack of prepared statements. And a database related function that decides on its own whether to output an error or not, as though database interaction is something different from other code.

帮个忙,用这个方法使这个功能

Do yourself a favor, make this function this way

function query($query, $parameters = []) {
    $pdo = // here your way of getting a PDO instance. 
    // DON't TELL ME YOU ARE CREATING A NEW ONE EVERY TIME
    if (!$parameters)
    {
         return $this->query($sql);
    }
    $stmt = $pdo->prepare($sql);
    $stmt->execute($parameters);
    return $stmt;
}

这就是您所需要的,并且比您目前拥有的要好得多.

This is ALL you need and it's MUCH better than you have at the moment.

返回语句是关键.它使您可以将所需的任何提取方法附加到函数调用上-这是从此类函数获取不同结果类型的最自然的方法.或者,如果查询恰巧是UPDATE或INSERT,则根本不获取任何内容.

Returning a statement is the key. It lets you to attach any fetch method you like to the function call - the most natural way of getting different result types from such a function. Or not to fetch anything at all, if a query happens to be UPDATE or INSERT.

要计数吗?

$count = query("DELETE FROM usars")->rowCount();

要获取吗?

$user = query("select * from users where id=?", [$id])->fetch();

是否希望通过PDO :: FETCH_COLUMN获取fetchAll?你在这里

want fetchAll with PDO::FETCH_COLUMN? here you are

$users = query("select name from users")->fetchAll(PDO::FETCH_COLUMN);

简单,可用,灵活,易读且安全.

Simple, usable, flexible, readable and secure.

如果您不知道如何使此功能仅连接一次,则这里是指向简单 PDO的链接包装器我写的. 请注意示例部分.令人兴奋的是,我***把它放在这里:

If you don't know how to make this function connect only once, here is a link to a simple PDO wrapper I wrote. Note the examples section. It is so exciting that I'd better put it here:

# Table creation
DB::query("CREATE temporary TABLE pdowrapper 
           (id int auto_increment primary key, name varchar(255))");

# Prepared statement multiple execution
$stmt = DB::prepare("INSERT INTO pdowrapper VALUES (NULL, ?)");
foreach (['Sam','Bob','Joe'] as $name)
{
    $stmt->execute([$name]);
}
$id = DB::lastInsertId());

# Getting rows in a loop
$stmt = DB::run("SELECT * FROM pdowrapper");
while ($row = $stmt->fetch())
{
    echo $row['name'], PHP_EOL;
}

# Getting one row
$id  = 1;
$row = DB::run("SELECT * FROM pdowrapper WHERE id=?", [$id])->fetch();

# Getting single field value
$name = DB::run("SELECT name FROM pdowrapper WHERE id=?", [$id])->fetchColumn();

# Getting array of rows
$all = DB::run("SELECT name, id FROM pdowrapper")->fetchAll(PDO::FETCH_KEY_PAIR);

# Update
$new = 'Sue';
$count = DB::run("UPDATE pdowrapper SET name=? WHERE id=?", [$new, $id])->rowCount();