Colin
Colin

Reputation: 1142

Get the result of the sql query in a variable

I have a simple MySQL Database setup.

enter image description here

When I execute in 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.

$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. Can you help me with that lines that are missing here?

Thank you very much.

Upvotes: 1

Views: 58

Answers (3)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

First of all, you didn't bind your variable, so bind your variable using ->bindParam() first. And second, use ->fetch(PDO::FETCH_ASSOC) to get the row from the result set.

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

Upvotes: 1

massquote
massquote

Reputation: 4617

Try it like this

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

Upvotes: 0

drosam
drosam

Reputation: 2896

You need to fetch the result after execute() the query. For example:

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

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

Upvotes: 0

Related Questions