简体   繁体   English

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

[英]Get the result of the sql query in a variable

I have a simple MySQL Database setup. 我有一个简单的MySQL数据库设置。

在此处输入图片说明

When I execute in MySQL shell: 当我在MySQL Shell中执行时:

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

it says: 它说:

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

which is correct. 哪个是对的。 In php i want one variable having the value 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;

But this does not work. 但这是行不通的。 The $result does not have the value 4 . $result没有值4 Can you help me with that lines that are missing here? 您能帮我解决这里缺少的内容吗?

Thank you very much. 非常感谢你。

First of all, you didn't bind your variable, so bind your variable using ->bindParam() first. 首先,您没有绑定变量,因此请首先使用->bindParam()绑定变量。 And second, use ->fetch(PDO::FETCH_ASSOC) to get the row from the result set. 其次,使用->fetch(PDO::FETCH_ASSOC)从结果集中获取行。

So your code should be like this: 因此,您的代码应如下所示:

$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'];
}

You need to fetch the result after execute() the query. 您需要在execute()查询之后获取结果。 For example: 例如:

$result = $statement->execute()->fetchAll();

See http://php.net/manual/en/pdostatement.fetchall.php 参见http://php.net/manual/en/pdostatement.fetchall.php

Try it like this 像这样尝试

$dt = $statement->execute();
$result = $dt->fetch();
var_dump($result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM