在绑定PDO参数后构建响应数组

时间:2015-01-08 01:30:52

标签: php pdo

我正在尝试构建将返回到我的ajax成功的数组。如何在将数组绑定到类似的变量之后构建数组:

以下脚本运行完成,并且没有任何问题插入到sql中。但是变量comment和transaction在响应中返回null。我认为问题是在构建数组时使用$ comment和$ transaction。在数组中引用这些值的正确方法是什么?

        require('../dbcon2.php');
        //Connection 1
        try {
          $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
          $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          $stmt = $conn->prepare("UPDATE listings SET comment = :comment, transaction = :transaction, ad_link = :ad_link WHERE id = :id");
            // Bind
            $stmt->bindParam(':id', $_POST['id']);
            $stmt->bindParam(':comment', $_POST['comment']);
            $stmt->bindParam(':transaction', $_POST['transaction']);
          $stmt->execute();
          // Build array
           $response = array
                 ('state'  => 200, "success" => true, "id" => ':id', "comment" => $comment, "transaction" => $transaction 
                 );
          exit(json_encode($response));

        }
    catch (Exception $e) {
                // create a asociative array
                $data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
                // encode data and exit.
                exit(json_encode($data));
            }

enter image description here

2 个答案:

答案 0 :(得分:2)

根据OP的愿望:

按照"id" => ':id'

的方式进行操作
"id" => ':id', "comment" => ':comment', "transaction" => ':transaction'

另外,引用Jeroen(kudos to)

为什么不使用$_POST变量?它包含您需要的值,并且您已在数据库查询中使用它们。

答案 1 :(得分:1)

调用->bindParam()后,您无法检索绑定值;此外,变量$comment$transaction尚未定义(除非您自己设置或使用voodoo php设置)。

那就是说,你已经知道了这些价值观:

$response = array(
   'state'        => 200, 
    "success"     => true, 
    "id"          => $_POST['id'], 
    "comment"     => $_POST['comment'], 
    "transaction" => $_POST['transaction'], 
);

顺便说一下,在异常分支中你有一个小bug:

$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
                                                                   ^

您应该使用$e->getMessage()代替。

相关问题