如何从mysqli查询中获取结果数?

时间:2017-03-26 16:20:00

标签: php mysql mysqli

所以我正在做这个查询:

'SELECT * FROM Album WHERE id = ?;'

使用prepare sql语句,我想知道如何获取此查询返回的结果数量? B / c,因为每个专辑ID都是唯一的,这个查询应该只返回1张专辑,我想确保它这样做。

代码

$stmt = $mysqli->prepare('SELECT * FROM Album WHERE id = ?;');
$id = 2;
$stmt->bind_param('i', $id);
$executed = $stmt->execute();
$result = $stmt->get_result();
if($row = $result->fetch_assoc()){
    $info['id'] = $row['id'];
    $info['title'] = $row['title'];
    $info['date_created'] = $row['date_created'];
    $info['creator'] = $row['creator'];
}
// Send back the array as json
echo json_encode($info);

3 个答案:

答案 0 :(得分:1)

您可以使用 define( 'API_ACCESS_KEY', 'xxxxxxxxxxxxxxxxxxxxx'); $url = 'https://fcm.googleapis.com/fcm/send'; $priority="high"; $notification= array('title' => 'Some title','body' => 'hi', "priority" =>"high", ); $tokens = array('Token-1','token-2'); $fields = array( 'registration_ids' => $tokens, 'notification' => $notification ); $headers = array( 'Authorization:key='.API_ACCESS_KEY, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); // echo json_encode($fields); $result = curl_exec($ch); echo curl_error($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } curl_close($ch); echo $result;

来获取它

您可以在PHP Documentation找到更多详细信息。

答案 1 :(得分:0)

  

我想确保它这样做

在您的代码中,您已经在这样做了。以下条件

if($row = $result->fetch_assoc()){

完全符合您的要求

此致
你的常识

答案 2 :(得分:-1)

只需使用COUNT(*)

SELECT COUNT(*) FROM Album WHERE id = ?;

参考: https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html

另一种方式

$query = $dbh->prepare("SELECT * FROM Album WHERE id = ?");
$query->execute();
$count =$query->rowCount();
echo $count;