[英]Json loop prepared statement
我怎樣才能從數據庫中獲取所有數據? 僅1個json數據:
{“錯誤”:false,“用戶”:{“ product_id”:42,“ product_name”:“帶無限米飯的雞肉”,“ product_description”:“”,“ product_image”:“ http://www.migrandegensan。 com / image / 1.jpg“}}
這是我的代碼:
Chicken.php
<?php
require_once 'include/db_functions.php';
$db = new DB_Functions();
$response = array("error" => FALSE);
//select data from chicken
$user = $db->getID();
if ($user) {
$response["error"] = FALSE;
$response["user"]["product_id"]=$user["product_id"];
$response["user"]["product_name"] = $user["product_name"];
$response["user"]["product_description"] = $user["product_description"];
$response["user"]["product_image"] = $user["product_image"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
?>
db_functions.php
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'db_connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
public function getID() {
$pro_cat_id = "101";
$stmt = $this->conn->prepare("SELECT * FROM products WHERE pro_cat_id = ?");
$stmt->bind_param("s", $pro_cat_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
while ($user) {
return $user;
}
}
}
?>
提前致謝!
請嘗試以下代碼:Chicken.php
require_once 'include/db_functions.php';
$db = new DB_Functions();
$response = array("error" => FALSE);
//select data from chicken
$user = $db->getID();
if ($user) {
$response["error"] = FALSE;
foreach ($user as $key => $value) {
# code...
$response["user"]["product_id"]=$value["product_id"];
$response["user"]["product_name"] = $value["product_name"];
$response["user"]["product_description"] = $value["product_description"];
$response["user"]["product_image"] = $value["product_image"];
}
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
?>
db_functions.php
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'db_connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
public function getID() {
$pro_cat_id = "101";
$stmt = $this->conn->prepare("SELECT * FROM products WHERE pro_cat_id = ?");
$stmt->bind_param("s", $pro_cat_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
}
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.