Extracting data from a database into array - php

I'm building an angular application, so I have a PHP script extracting the database data into a JSON when requested.
This is what I'm using to extract the data into an array:
$values = array();
$query = "SELECT * FROM photos ORDER BY id";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
array_push($values, $row);
}
json_encode($values);
But it gives no result.
After some testing, if I change json_encode($values); to print_r($values); it actually print the table array, here an extract:
Array (
[0] => Array (
[id] => 4
[title] => Feel the Moment
[views] => 6
)
It seems the script is not creating a valid array.

$query = "SELECT * FROM photos ORDER BY id";
if ($result = $this->mysqli->query($query)) {
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = $row;
}
echo json_encode($json);
}

Your while is not executing, probably because you don't have any returned values from database.
I tested this code and it works well:
$json = array();
$json[] = array(
"id" => 1,
"category" => 'a',
"tags" => 't');
$json[] = array(
"id" => 2,
"category" => 'b',
"tags" => 'tt');
echo json_encode($json);
The result is:
[{"id":1,"category":"a","tags":"t"},{"id":2,"category":"b","tags":"tt"}]
And you'd better use mysqli_fetch_row or mysqli_fetch_assoc.
Try to debug your code. You may use var_dump($result->fetch_assoc()) to see if the query has some results.

Related

Acces nested json

Please, help me a bit, i tried in any possible way to acces a nested json data, but without succes.
json
string(701) "{"status":"SUCCESS","products":{"6605995":{"is_bundle":false,"ean":"5949234930002","sku":"KNK-BAN-MP","tax_rate":19,"weight":0,"height":0,"width":0,"length":0,"star":0,"category_id":647123,"manufacturer_id":174472,"text_fields":{"name":"Bandaje Box Knockout Balcescu"},"stock":{"bl_11206":79},"prices":{"10929":69},"locations":{"bl_11206":""},"links":{"shop_4000268":{"product_id":"6665093873699","variant_id":"0"}},"average_cost":0,"average_landed_cost":0,"images":{"1":"https:\/\/cdn.shopify.com\/s\/files\/1\/0273\/9034\/5251\/products\/image.jpg?v=1657567836","2":"https:\/\/cdn.shopify.com\/s\/files\/1\/0273\/9034\/5251\/products\/image_37af2a9f-83c9-4a1f-84d6-3ad0e6aa62a3.jpg?v=1657567836"}}}}"
SCRIPT details above, basically, i need to replacesome how [static product id] details in comments
$arr = [
'inventory_id' => $inventoryid,
'products' => []
];
$q = $dbc->query("SELECT bpID FROM Products LIMIT 3");
while($row = mysqli_fetch_assoc($q)) {
$bpID = $row['bpID'];
$arr['products'][] = $row['bpID'];
}
$getproductidsp = [
'method' => 'getInventoryProductsData',
'parameters' => json_encode($arr),
];
$ch = curl_init();
$output = curl_exec($ch);
$data = json_decode($output, true);
var_dump($data);
foreach($data['products'][$bpID]['links'] as $key => $val){
$prod = $val['product_id'];
$variant = $val['variant_id'];
$query = "UPDATE IGNORE Products SET spID='$prod', svID='$variant' WHERE bpID='$bpID';";
$result = mysqli_query ($dbc, $query) or die (mysqli_error($dbc));
echo $result;
mysqli_close($dbc);
from the provided data, it works
foreach($data['products'][6605995]['links'] as $key => $val){
print_r($val);
}
and result is
Array
(
[product_id] => 6665093873699
[variant_id] => 0
)
working demo -> here
in the foreach ['links'], the key is shop and the product_id and variant_id are the values
foreach($data['products'][6605995]['links'] as $key => $val){
$prod = $val['product_id'];
$variant = $val['variant_id'];
}
edit2: looping products

get string when trying to make a dynamic json list / array

I am trying to make a dynamic JSON array in PHP, however when I try to do so it returns "Array". Here is the code I am currently using:
<?php
require '../../scripts/connect.php';
$array = '';
if($result = $db->query("SELECT * FROM art") or die ($db->error)){
if($count = $result->num_rows) {
while($row = $result->fetch_object()){
$array .= array(
'title' => $row->title,
'image' => "http://www.thewebsite.com/img/2.jpg",
'rating' => 7.7,
'releaseYear' => 2003,
'genre' => array(
'0' => $row->category,
'1' => $row->subcategory
)
);
}
}
}
echo json_encode($array);
?>
Can anyone suggest how I might go about fixing this?
And if anyone has suggestions about creating a dynamic JSON array, some help would be much appreciated.
Change your declaration of $array to be an array:
$array = array();
Then in your while loop, when you add the new array to $array, push it like this:
$array[] = array('title'=>$row->title, etc...)

Handling foreach or forloop with array values PHP MYSQL

Output Array (The variable name is $r)
Array
(
[Jan-14] => 7588793.52
[Feb-14] => 9944970.87
[Mar-14] => 8567790.20
[Apr-14] =>
[May-14] =>
[Jun-14] =>
[Jul-14] =>
[Aug-14] =>
[Sep-14] =>
[Oct-14] =>
[Nov-14] =>
[Dec-14] =>
)
What I have done so far is..
while($r = mysql_fetch_assoc($query)) {
$series1['data'][] = $r['Jan-14'];
$series2['data'][] = $r['Feb-14'];
.... it will go till Dec-14.......
array_push($result,$series1);
array_push($result,$series2);
.... it will go till Dec-14.......
}
Expected Output:
The code should look something like this this (dynamic)
while($r = mysql_fetch_assoc($query)) {
for($i=1;$i<=count($r);$i++){
$series.$i['data'][] = ??????????
array_push($result,$series.$i);
..................
}
}
Help me out. Don't talk about the db structure or normalization. The db was given by my client.
Thanks,
Kimz
Do you mean like this?
$result = array();
foreach($r as $month => $value) {
$result[] = array('data' => array($value));
}

how to use array_push for json_encode

I am iOS developer and I am making Webservices in PHP for getting JSON Response.
Code which I wrote is:
$result = mysqli_query($con,"SELECT * FROM wp_marketcatagories");
$data =array();
while($row = mysqli_fetch_array($result))
{
$data[] = array_push($data, array('id' => $row['id']));
}
$json = json_encode($data);
echo $json;
This is what I want in result:
[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"},{"id":"6"},{"id":"7"},{"id":"8"},{"id":"9"},{"id":"10"},{"id":"11"},{"id":"12"}]
But above code is giving me like this:
[{"id":"1"},1,{"id":"2"},3,{"id":"3"},5,{"id":"4"},7,{"id":"5"},9,{"id":"6"},11,{"id":"7"},13,{"id":"8"},15,{"id":"9"},17,{"id":"10"},19,{"id":"11"},21,{"id":"12"},23]
From where this 1, 3, 5 ,.... are coming ?
no need to assign it to $data[]. You are already pushing the values to the array $data
Just simply use
array_push($data, array('id' => $row['id']));
instead of
$data[] = array_push($data, array('id' => $row['id']));
Array_Push(): Returns the new number of elements in the array.
...this is were your numbers are coming from and you're adding them to the array with your $data[] = statement
array_push($data, array('id' => $row['id']));
or
$data[] = array('id' => $row['id']);
Same result in this scenario
You don't require to assign $data twice as you have written like this:
$data[] = array_push($data, array('id' => $row['id']));
array_push — Push one or more elements onto the end of array
syntax : array_push(array,value1,value2...)
Just write
array_push($data, array('id' => $row['id']));
or
$data[] = array('id' => $row['id']);

Ouput data in JSON format on Array in PHP

$result = mysql_query($query);
$leaderboard = array();
while($row = mysql_fetch_assoc($result)) {
$leaderboard[$row["username"]] = $row["score"];
}
$output = array
(
'status' => 1,
'content' =>$leaderboard
);
print_r(json_encode($output));
right now the $output array is such JSON:
{"tim":"120","john":"45","larry":"56"}
but I want to have them as key-value pair so instead I want to be like:
{"name":"tim","score":120","name":"john","score="45", etc.}
and if I need that way, how do I modify the $leaderboard array so the output would be like that?
$leaderboard[] = Array('name' => $row["username"], 'score' => $row["score"]);

Categories