gpt4 book ai didi

php - 在变量中获取sql查询的结果

转载 作者:行者123 更新时间:2023-11-28 23:38:35 25 4
gpt4 key购买 nike

我有一个简单的 MySQL 数据库设置。

enter image description here

当我在 MySQL shell 中执行时:

“SELECT count(serverid) as num FROM servers WHERE owner_id = 1”

它说:

+-----+
| num |
+-----+
| 4 |
+-----+

这是正确的。在 php 中,我想要一个值为 4 的变量。

$pdo = new PDO('mysql:host=localhost;dbname=cswebin', 'root', 'password');
$statement = $pdo->prepare("SELECT count(serverid) as num FROM servers WHERE owner_id = :useruid");
$result = $statement->execute();
echo $result;

但这行不通。 $result 没有值 4。你能帮我解决这里缺少的那几行吗?

非常感谢。

最佳答案

首先,您没有绑定(bind)您的变量,因此请先使用->bindParam() 绑定(bind)您的变量。其次,使用 ->fetch(PDO::FETCH_ASSOC) 从结果集中获取行。

所以你的代码应该是这样的:

$useruid = <YOUR VALUE>;

$pdo = new PDO('mysql:host=localhost;dbname=cswebin', 'root', 'password');
$statement = $pdo->prepare("SELECT count(serverid) as num FROM servers WHERE owner_id = :useruid");
$statement->bindParam(':useruid', $useruid);
if($statement->execute()){
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo $row['num'];
}

关于php - 在变量中获取sql查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35066463/

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