[英]Building a response array after binding parameters for PDO
I am trying to build the array that will return to my ajax success. 我正在尝试构建将返回我的Ajax成功的数组。 How do I build the array after binding it to something like :some variable.
将数组绑定到类似:some变量后,如何构建数组。
The following script runs to completion, and inserts with no problem into sql. 以下脚本运行完毕,并且毫无问题地插入到sql中。 But the variables comment and transaction come back as null in the response.
但是变量注释和事务在响应中返回为空。 I think the problem is using $comment and $transaction when building the array.
我认为问题是在构建数组时使用$ comment和$ transaction。 What is the right way to reference these values in the array?
在数组中引用这些值的正确方法是什么?
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));
}
As per OP's wish: 按照OP的愿望:
Do as you did for "id" => ':id'
像对
"id" => ':id'
"id" => ':id', "comment" => ':comment', "transaction" => ':transaction'
Plus, quoting Jeroen (kudos to) 另外,引述Jeroen(致敬)
Why don't you use the $_POST
variable? 为什么不使用
$_POST
变量? That contains the values you need and you use them already in your database query. 包含所需的值,并且已在数据库查询中使用它们。
You can't retrieve bound values after calling ->bindParam()
; 调用
->bindParam()
后,您将无法检索绑定值; also, the variables $comment
and $transaction
aren't defined (unless you set them yourself or when using voodoo php settings). 同样,没有定义变量
$comment
和$transaction
(除非您自己设置它们或使用voodoo php设置)。
That said, you already know those values: 也就是说,您已经知道这些值:
$response = array(
'state' => 200,
"success" => true,
"id" => $_POST['id'],
"comment" => $_POST['comment'],
"transaction" => $_POST['transaction'],
);
Btw, in the exception branch you have a small bug: 顺便说一句,在异常分支中,您有一个小错误:
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
^
You should use $e->getMessage()
instead. 您应该使用
$e->getMessage()
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.