Reputation: 81
I have a sql table with products and i don't get how to retrieve several products using array with their ids
i know how retrieve all of these products and only one using id
JSON with all products from sql
function loadGoods(){
$conn = connect();
$sql = "SELECT * FROM PRODUCTS";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$out = array();
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$out[$row["id"]] = $row;
}
echo json_encode($out);
} else {
echo 0;
}
mysqli_close($conn);
}
JSON with one product using its id received in js file from hash
function loadSingleGoods(){
$id = $_POST['id'];
$conn = connect();
$sql = "SELECT * FROM PRODUCTS WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
echo json_encode($row);
} else {
echo 0;
}
}
Both of these snippets are working and now i have array with id's but i don't get how retrieve only their properties from sql in JSON file.
I have array with ids like this ["6", "7", "27"] and i need to retrieve from sql PRODUCTS only items with these ids. As i understand i have to do something with this line
$sql = "SELECT * FROM PRODUCTS WHERE id='$id'";
i tried such code
$sql = "SELECT * FROM PRODUCTS WHERE in_array("id", $ids, TRUE);
but it didn't work
Upvotes: 3
Views: 745
Reputation: 58
You can build your query before executing it:
$sql_array=array("6", "7", "27");
$first_item=array_values($sql_array)[0];
$sql="SELECT * FROM `PRODUCTS` WHERE `id`='$first_item'";
$built_query="";
foreach ($sql_array as $k => $id) {
if ($k < 1) continue;
$built_query=$built_query." OR `id` = '$id'";
}
$built_query=$sql.$built_query;
echo "$built_query";
Upvotes: 0
Reputation: 3261
You can parse json object using JSON.parse()
and access all the value of the object.
var text = '{ "name":"John", "age":"39", "city":"New York"}';
JSON.parse(text, function (key, value) {
console.log(value);
});
Here you can replace text
with your json
variable.
If you want to read more about json parse & how to access json variable in js click here.
Upvotes: 3
Reputation: 5192
It would be helpful if you showed us your JavaScript also, but assuming you're feeding the output of the json_encode()
into a single variable, you can access each product like so:
console.log(json_variable[0]);
That should give you the first "row". To access a particular cell, try this:
console.log(json_variable[0]['column_name']);
To go thru all of them, try jQuery's each()
:
$.each( json_variable, function( id, column_name) {
console.log( id + ": " + column_name);
});
Upvotes: 4