Php 在变量中获取sql查询的结果
我有一个简单的MySQL数据库设置 当我在MySQL shell中执行时:Php 在变量中获取sql查询的结果,php,mysql,Php,Mysql,我有一个简单的MySQL数据库设置 当我在MySQL shell中执行时: “从所有者id=1的服务器中选择count(serverid)作为num” 它说: +-----+ | num | +-----+ | 4 | +-----+ 这是正确的。 在php中,我需要一个值为4的变量 $pdo = new PDO('mysql:host=localhost;dbname=cswebin', 'root', 'password'); $statement = $pdo->prepa
“从所有者id=1的服务器中选择count(serverid)作为num”
它说:
+-----+
| 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
。你能帮我弄一下这里缺的那几行吗
非常感谢。您需要在
execute()
查询之后获取结果。例如:
$result = $statement->execute()->fetchAll();
请参见像这样尝试
$dt = $statement->execute();
$result = $dt->fetch();
var_dump($result);
首先,您没有绑定变量,所以首先使用
->bindParam()
绑定变量。其次,使用->fetch(PDO::fetch\u 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'];
}
$useruid=;
$pdo=newpdo('mysql:host=localhost;dbname=cswebin','root','password');
$statement=$pdo->prepare(“选择count(serverid)作为来自owner_id=:useruid的服务器的num”);
$statement->bindParam(':useruid',$useruid);
如果($statement->execute()){
$row=$statement->fetch(PDO::fetch_ASSOC);
echo$row['num'];
}
查看bindValue()
和fetch()
以及fetch.*
上的PDO
$result
函数将是一个数组,因此您可能打算执行打印($result)
或回显$result['num']代码>可能…或使用列表($result)=$dt->fetch(PDO::fetch_NUM);好吧,我想就这样吧。