fetch_object()--6ren">
gpt4 book ai didi

php - MySQLi 准备好的语句 : Short versions in one line

转载 作者:行者123 更新时间:2023-11-29 12:09:53 25 4
gpt4 key购买 nike

在 PHP 中,我使用了很多单行代码,例如:

获取值:

$sql->query("SELECT ID FROM table WHERE condition = 1")->fetch_object()->ID;

获取行:

$sql->query("SELECT * FROM table WHERE condition = 1")->fetch_assoc();

获取行:

$sql->query("SELECT * FROM table WHERE condition > 1")->fetch_all(MYSQLI_ASSOC);

插入行:

$sql->query("INSERT INTO table(`row1`,`row2`) VALUES('".$data1."','".$data2."')");

删除行:

$sql->query("DELETE FROM table WHERE condition = 1");

还有漂亮的单行文字用于准备好的陈述吗?

这失败了:

$sql->prepare("SELECT ID FROM table WHERE condition = ?")->bind_param("i", $a=1)->execute()->fetch_object()->ID;

这有效:

$query = $sql->prepare("SELECT ID FROM table WHERE condition = ?");
$query->bind_param("i", $a=1);
$query->execute();
$query->get_result()->fetch_object()->ID;

最佳答案

直接 - 没有办法。但是您可以使用一个简单的覆盖类来实现这一点。

class PrepareOverlay {
private $stmt;
private $lastResult = null;

public function __construct(PDOStatement $stmt) {
$this->stmt = $stmt;
}

public function __call($name, $arguments) {
$this->lastResult = call_user_func_array([$this->stmt, $name], $arguments);
return is_bool($this->lastResult) ? $this : $this->lastResult;
}

public function getLastResult() {
return $this->lastResult;
}

public static function prepare($sql, $query) {
return new self($sql->prepare($query));
}
}

并像这样使用它:

PrepareOverlay::prepare($sql, 'SELECT * FROM table WHERE cond = ?')->bindParam('i', $a=1)->execute()->fetchObject()->ID;

尽管您需要一些 phpdoc 才能使代码完成工作。

关于php - MySQLi 准备好的语句 : Short versions in one line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30877577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com