我有一个查询,用于检查表中是否存在该值。然后将结果存储在数组中,并以JSON输出。但是我的回答总是:[{“ SELECT EXISTS(SELECT * FROM wp_woocommerce_order_items WHERE order_id = $ sdata)”:“ 1”}; 我只想让它输出结果(0或1) 这是我的代码:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT EXISTS(SELECT * FROM wp_woocommerce_order_items WHERE order_id = $sdata)";
if ($result = mysqli_query($conn, $query)) {
$newArr = array();
/* fetch associative array */
while ($db_field = mysqli_fetch_assoc($result)) {
$newArr[] = $db_field;
}
echo json_encode($newArr); // get all products in json format.
}
$conn->close();
?>
答案 0 :(得分:2)
首先,我建议您使用准备好的语句。
第二,将查询作为数组键,因为结果没有别名,所以这就是为什么要在数组中看到它。
第三,您这里确实不需要EXISTS
。
第四,您在这里也不需要循环
$query = "SELECT COUNT(*) FROM wp_woocommerce_order_items as item_exists WHERE order_id = $sdata";
if ($result = mysqli_query($conn, $query)) {
$newArr = array();
$value = mysqli_fetch_object($result);
$newArr[] = (bool) $value->item_exists;
echo json_encode($newArr); // get all products in json format.
}
使用准备好的语句:
$stmt = $mysqli->prepare('SELECT COUNT(*) as item_exists FROM wp_woocommerce_order_items WHERE order_id = ?');
$stmt->bind_param("i", $sdata);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->close();
echo json_encode((bool) $row['item_exists']);