如何获取SQL语句的行数

时间:2019-04-20 08:19:12

标签: php html

是否可以获得语句的行数?

我尝试

$stmt2 = $pdo->query("SELECT count(*) FROM `participation` 
   WHERE id_evenement = '$id_event' 
   AND id_membre_participation ='$id_membre'");

if ($stmt2 == 0) { 
   echo 'ok'; 
} else { 
   echo 'no';
} 

但是我有这个错误:

Notice: Object of class PDOStatement could not be converted to int in C:\wamp64\www\projet\[...] on line 55
no

该陈述是正确的,如果我在php我的管理员中尝试过这个话:

SELECT count(*) FROM `participation` WHERE id_evenement = 9 AND id_membre_participation = 1

我有

+----------+
| count(*) |
+----------+
|     1    |
+----------+

如果我将id_membre_participation更改为2:

SELECT count(*) FROM `participation` WHERE id_evenement = 9 AND id_membre_participation = 2
+----------+
| count(*) |
+----------+
|     0    |
+----------+

有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

是的,您可以使用fetchColumn获取行数

$sql = "SELECT count(*) FROM `table` WHERE foo = bar"; 
$result = $con->prepare($sql); 
$result->execute(); 
$number_of_rows = $result->fetchColumn();

答案 1 :(得分:1)

PDO::query将结果集作为PDOStatement对象返回,您必须从中获取实际数据。在这种情况下,您只有一个值,可以通过调用PDOStatement::fetchColumn来检索。试试这个:

$stmt2 = $pdo->query("SELECT count(*) FROM `participation` 
   WHERE id_evenement = '$id_event' 
   AND id_membre_participation ='$id_membre'");
$count = $stmt2->fetchColumn(0);
if ($count == 0) { 
   echo 'ok'; 
} else { 
   echo 'no';
}