为什么使用bind_result分配的变量值为null?

时间:2019-01-30 07:00:06

标签: php

我正在使用POST方法获取id,并尝试使用bind_result()检索值和绑定结果,但是返回的值是null。我使用了以下代码。

    <?php
 //getting the database connection
 require_once 'configuration.php';

 //an array to display response
 $response = array();
 if($_POST['id']){
     $id = $_POST['id'];
     $stmt = $conn->prepare("SELECT name,price,description FROM products WHERE id = ?");
     $stmt->bind_param("i",$id);
     $stmt->fetch();
     $result = $stmt->execute();
     if($result == TRUE){
         $response['error'] = false;
         $response['message'] = "Retrieval Successful!";
         $stmt->store_result();
         $stmt->bind_result($name,$price,$description);
         $response['name'] = $name;
         $response['price'] = $price;
         $response['description'] = $description;
     } else{
         $response['error'] = true;
         $response['message'] = "Incorrect id";
     }
 } else{
      $response['error'] = true;
      $response['message'] = "Insufficient Parameters";
 }
 echo json_encode($response);
?>

JSON响应如下:

{"error":false,"message":"Retrieval Successful!","name":null,"price":null,"description":null}

有人可以告诉我代码有什么问题吗?

2 个答案:

答案 0 :(得分:0)

您可能会发现id在表中存储为整数。假设是这种情况,您需要更新参数。

 $stmt->bind_param("i",$id);

答案 1 :(得分:0)

只需发表评论作为答案...

原始代码根本不获取数据,修改后的代码在绑定之前称为fetch,您应该有...

$stmt->bind_result($name,$price,$description);
$stmt->fetch();