How to get mysql data from php to json? - php

My problem is to get data from SQL to dynamically update chart.
Mysql data is like this:
id | age
1 | 12
2 | 21
3 | 31
4 | 11
5 | 31
And I want to echo like this:
[1,12] , [2,21] , [3,31] , [4,11] , [5,31]
I have tried this:
$sql = "SELECT id, age FROM tes";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$tes = $row['tes'];
$a = array($id,$tes);
echo json_encode($a, JSON_PRETTY_PRINT);
}
But it ended like this:
[1,12] [2,21] [3,31] [4,11] [5,31]

Collect all the rows into a 2-D array, then return that as JSON.
$a = array();
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
$tes = $row['tes'];
$a[] = array($id,$tes);
}
echo json_encode($a, JSON_PRETTY_PRINT);

Related

Fetch Mysql Results into serialized data

I have this table:
| id | related_id |
| 1 | 100 |
| 1 | 200 |
| 1 | 300 |
| 2 | 400 |
| 2 | 500 |
| 2 | 600 |
I need to retrieve serialized data as:
a:3:{i:1;s:3:"100";i:2;s:3:"200";i:3;s:3:"300";}
Query
SELECT id, related_id from mytable where id = 1;
I'm trying to get this using 'while'
$result = $link->query($query);
$item = array();
while($f = $result->fetch_assoc()){
$id = $f['id'];
if ($id == $f['id']){
$item[] = $f['related_id'];
}
print serialize($item);
break; // for test
}
SOLUTION that works for me (provided by Erwin - Thanks!)
$item = array();
while($f = $result->fetch_assoc()) {
$id = $f['id'];
if (!array_key_exists($id, $item)) {
$item[$id] = [1 => $f['related_id']];
} else {
$item[$id][] = $f['related_id'];
}
}
foreach ($item as $value) {
print serialize($value) . PHP_EOL;
}
Collect first each related_id and store to id array with your while loop. Then print each using foreach.
$item = array();
while($f = $result->fetch_assoc()) {
$id = $f['id'];
if (!array_key_exists($id, $item)) { // create id array if not exist
$item[$id] = [1 => $f['related_id']]; // To start with index 1
} else {
$item[$id][] = $f['related_id']; // Push each new related_id
}
}
foreach ($item as $value) {
print serialize($value); // Print each serialized
echo '<br>'; // New line
}
What you are trying to do is something like this:
$result = $link->query($query);
$items = array();
while($f = $result->fetch_assoc()){
$id = $f['id'];
if(!isset($items[$id])) {
$items[$id] = array();
}
$items[$id][] = $f['related_id'];
}
foreach($items as $item) {
print serialize($item);
}
For your serialized string, you have to work with an array with related_id in the second layer. The first layer is to save all related_id in an array with the same id.
You have 6 rows, 3 have id 1 and 3 have id 2. You are specifying that you want to use these ids as array keys so you will end up with 2 arrays, each holding 3 values.
If you want each row in its own array you do this:
while($f = $result->fetch_assoc()){
$item[] = array($f['id'] => $f['related_id']);
}

php mysql match value from multiple values a column

I want to find a value from a column which has multiple values like (23,24,25), Using php mysqli query.
Table:
+-----------------+
id | tag_ids |
+-----------------+
1 | 3,4,5 |
2 | 3,7,8,9 |
3 | 4,5,10 |
Curent query:
$value = '3';
$query = "SELECT tag_ids FROM table WHERE FIND_IN_SET($value, tag_ids)";
$result = mysqli_query($query);
$count = mysqli_num_rows($result);
echo count;
Result will be: YES/NO or 1/0, if the Given value is match any value with tag_ids.
I found the result my self and here is code:
function statusvalues() {
$query = "SELECT tag_ids FROM tblname WHERE tag_ids !=''";
$result = mysqli_query($query, DBCONN);
$idarray = array();
while($row = mysqli_fetch_array($result)) {
array_push($idarray, $row['tag_ids']);
}
return $idarray;
}
function status($ID) { //Passing tag id
$set_of_numbers = statusvalues();
$reset_numbers = implode(", ", $set_of_numbers);
$values = explode(", ", $reset_numbers);
if (in_array($ID, $values)){
return "disabled";
}
}

Assign variables from array

I created a settings table in my database and I would like to assign value to a variable based on the setting and I'm not sure how to go about doing it.
table: settings
id | setting | value
1 | setting_one | value_one
2 | setting_two | value_two
3 | setting_three | value_three
Query
if ($result = $db->query("SELECT * FROM settings")) {
while($row = mysqli_fetch_assoc($result)) {
$SettingOne = $row['setting_one'];
$SettingTwo = $row['setting_two'];
$SettingThree = $row['setting_three'];
}
}
The select will return you 3 rows, assuming your table has only 3 rows in it
that is why you process the result in a while lop.
Each $row will contain an Assoc array in the form of the columns that you selected in your query.
In this case as you use SELECT * the $row array will contain 3 occurances
id, setting, value
So your loop should look like
if ($result = $db->query("SELECT * FROM settings")) {
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$setting = $row['setting'];
$value = $row['value'];
echo "The id = $id, the setting = $setting, the value is $value <br>";
}
}
This will produce you 3 lines of output, assuming you only have 3 rows in your table
I got it figured out and just echo the row['setting'] as $setting for each :)
if ($result = $db->query("SELECT * FROM settings")) {
while($row = mysqli_fetch_assoc($result)) {
$key = $row['setting'];
$$key = $row['value'];
}
$result->free();
$result->close();
}

How to create a JSON from table PHP

How to create a json like this in php;
[{"idorder":"34",
"totalOrder":"55",
"products":[{"idproduct":"5","price":"10"},{"idproduct":"4","price":"45"}]
}]
from table mysql;
+---------+-----------+--------------+
| idorder | idproduct | priceproduct |
+---------+-----------+--------------+
| 1 | 4 | 45 |
| 1 | 5 | 10 |
+---------+-----------+--------------+
my current code something.php;
...
$result = $conn->query($pendientesq);
$return_arr = array();
$productos = array();
$r1=$result->fetch_array();
$return_arr['idorder'] = $r1['idorder'];
$return_arr['totalOrder'] = '55';
//But now????How to create sub array with multiples products.
echo json_encode($return_arr);
you need to try something like this:
$r1=$result->fetch_array();
$return_arr['idorder'] = $r1['idorder'];
$return_arr['totalOrder'] = '55';
// suposse total products are 10
$product=10;
for($i=0;$i<product;$i++){
$return_arr['product'][] = array("idproduct"=>$i,"price"=>$i);//use your price and idproduct.
}
echo json_encode($return_arr);
I don't know how Your table looks like because You've not described it.
But I got for example "orders" table with idorder,idproduct,priceproduct fields.
And wrote this code:
// $q = "SELECT * FROM orders WHERE idorder = 5"; // for single order
$q = "SELECT * FROM orders";
$result = $conn->query($q);
$orders = [];
while($record=$result->fetch_array()) {
if(!isset($orders[$record['idorder']])) {
$orders[$record['idorder']] = [];
$orders[$record['idorder']]['idorder'] = $record['idorder'];
$orders[$record['idorder']]['totalOrder'] = 0;
$orders[$record['idorder']]['products'] = [];
}
$orders[$record['idorder']]['products'][] = ['idproduct' => $recrod['idproduct'],
'price' => $record['priceproduct']];
$orders[$record['idorder']]['totalOrder'] += $record['priceproduct'];
}
$orders = array_values($orders);
echo json_encode($orders);

How find Row Number of Value within Array?

I've saved all my data to an array, and I want to get the 'name' of a supplied 'code'.
How to I get the array row of that code?
Also, is this the most efficient process?
id | code | name |
__________________________
1 | KNTY | Kentucky |
2 | PURD | Purdue |
3 | TEXS | Texas |
// Move data to array
$search = "SELECT * FROM table";
$query = mysqli_query($conn, $search);
while($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
}
// Code I want a name for
$code = "KNTY";
// MYSTERY STEP I NEED HELP WITH
$name = $array[$id]['name'];
I edit with the hint of the comment of itachi. You can use the code as the key of the $array:
$search = "SELECT * FROM table";
$query = mysqli_query($conn, $search);
$array = array();
while($row = mysqli_fetch_assoc($query)) {
$array[$row['code']] = $row['name'];
}
// Code I want a name for
$code = "KNTY";
$name = $array[$code];
Yes you could do something like that, while inside the fetch loop, assign the code as key. This must be unique though:
$search = 'SELECT * FROM table_name';
$query = mysqli_query($conn, $search);
while($row = mysqli_fetch_assoc($query)) {
// assign `$row['code']` as key to this rowset
$array[$row['code']] = $row;
}
$code = 'KNTY';
if(isset($array[$code])) { // add some checking, you wouldn't want undefined index errors
$name = $array[$code]['name'];
echo $name;
} else {
echo 'Sorry not found';
}

Categories