JSON - No repeating table name - php

I have some problems with json..
I will let my code here, and i will show you what does it print to me, and what i need to be printed..
Well... this is my code:
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","3d") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$query = "SELECT team FROM hs";
$result = mysqli_query($connection, $query) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$arr = array();
while($row =mysqli_fetch_assoc($result))
{
$arr[] = $row;
}
echo json_encode($arr);
//close the db connection
mysqli_close($connection);
And it print me a json code, like:
[{"team":"coco"},{"team":"dada"},{"team":"fafa"},{"team":"momo"}]
My question is, how can i print a json code like this:
{"team":[["coco"],["dodo"]...]}
Another question is, how can i print a json code like this: (I want to group 2 teams, like a power of 2...
{"team":[["coco","dada"],["fafa","momo"]]}
Thank you, and have a nice day...

You need to form a proper array in your php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","3d") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$query = "SELECT team FROM hs";
$result = mysqli_query($connection, $query) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$arr = $new_arr = array();
while($row =mysqli_fetch_assoc($result))
{
$arr[] = $row['team'];
}
shuffle($arr);
$new_arr['team'] = array_chunk($arr, 2);
echo json_encode($new_arr);
//close the db connection
mysqli_close($connection);

The thing that is getting printed is a json array which consists of JSON objects hence you see the result like:
[{"team":"coco"},{"team":"dada"},{"team":"fafa"},{"team":"momo"}]
What I would suggest is, you should create a json array and keep adding json objects to it.
JSONArray team = new JSONArray();
team.add("coco");
team.add("dodo");
and so on.
Coming to your second doubt, create json arrays which will contain pairs of elements such as coco and dodo in one, foo and bar in other. Let's call these arrays arr1 and arr2.
Now create the main JSON array named team and do the following:
team.put(arr1);
team.put(arr2);
And you'll see the result you want. Do ask for clarifications if any. :)

Related

SHOW TABLES not returning correct items in array

I have multiple tables named like so MOM2016, MOM2017, MOM2018.
When i run query in phpmyadmin
SHOW TABLES LIKE 'MOM%'
it returns 3 items as expected.
BUT!!!! When i run in php, my code seem to give me only 1 item in the array (first one only MOM2016).
$sql = "SHOW TABLES LIKE 'MOM%'";
$result = $conn->query($sql);
$dbArray = $result->fetch_assoc();
echo "DEBUG:".count($dbArray);
This give:
DEBUG:1
My php code is wrong? Pls help.
If you want to get all the results at once,
$dbArray = $result->fetch_all();
echo "DEBUG:".count($dbArray);
Iterate through your fetch resource
$dbArray = array();
while ($row = $result->fetch_assoc()) {
$dbArray[] = $row;
}
print "DEBUG: " . count($dbArray);

how to retrieve value only of JSON by php from database?

may I know how to retrieve the value only array in json instead of the whole json object in php from the database?
<?php
require_once('dbConnect.php');
$sql = "SELECT RestaurantName FROM Restaurant";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$restaurantArray = array();
while($rows = mysqli_fetch_assoc($result)) {
$restaurantArray[] = $rows;
}
echo json_encode($restaurantArray);
mysqli_close($connection);
?>
For example,
["Afonso Cláudio", "Água Doce do Norte"]
instead of
[{"city":"Afonso Cláudio"},{"city":"Água Doce do Norte"}]
When fetching data from the database as assoc, you will get an associative array (which when converted to json will become a json object) as result.
What you are currently doing is adding the row (which is an associative array with one key-value) to your result array. If you only want the city, you can easily fetch only that data from the assoc-array.
Changing
$restaurantArray[] = $rows;
to
$resturantArray[] = $rows['city'];
should do the trick.
Additionally, if you wanted to reformat the data in the result, and not just push the city name to it, a array_map call could be used:
$result = array_map(function($assocArr) {
return $assocArr['city']; // Or whatever you want the value to be.
},
$resturantArray);
echo json_encode($result);
How about you change this line:
$restaurantArray[] = $rows;
With:
$restaurantArray[] = $rows['city']; // (or 'RestaurantName')

Populating array in PHP from MySQL table

I am newbie to PHP and need to seek your help on how to populate the array which is $dataArray[] with the rows of MySQL so that I will be able to call the data Array in some other function or say I want to print the $dataArray as above. I would be thankful to you if you can provide me example code modifications in my below code
<?php
$dataArray=array();
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT reg_date,xyz,pqr FROM stuvw";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$test = mysqli_num_rows($result);
echo $test;
while($row = mysqli_fetch_assoc($result))
{
$populate = '"' . $row["reg_date"]. '"'."=>" . $row["xyz"]. ", " ;
$dataArray[$populate] = $test;
}
echo $dataArray[$populate];
}
mysqli_close($conn);
?>
You can use an Associative array. This stores the data in a key-value format.
$dataArray[ $row['reg_date'] ] = $row['xyz'];
What you are doing in you example is creating a string in the $populate variable and using it as a key in the $dataArray. The number of rows returned from the SQL query is then stored as the value for each item in the $dataArray. This number is in the $test variable.
The key needs to be unique however so it makes sense to use the primary key from your MYSQL result as you key (if necessary).
Have a read through W3Schools PHP course.
http://www.w3schools.com/php/php_arrays.asp

Running two select queries in php and encoding it in json format?

I have two tables billing_all and payment_details. I am trying to write php code such that I can run the 2 queries in the same php code and encode their data in json format.I am currently using the following code to achieve that without json encode :-
<?php
include "config.php";
$dbname ="webappdb";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con)
{
echo "Connection Error".mysqli_connect_error();
}
else{
//echo "";
}
$sql = "SELECT SUM(total_wt) FROM `billing_all` WHERE date ='15-Apr-2016';";
$sql .= "SELECT pymt_amount, mode_of_pymt FROM `payment_details` WHERE DATE ='15-Apr-2016';";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf("%s%s\n",$row[0],$row[1]);
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
How can I encode the received data in json format? I tried something like:-
// Store first result set
if ($result=mysqli_store_result($con))
{
$r = array();
while($row = mysqli_fetch_array($result))
{
array_push($r,
array('total_wt'=>$row[0],
'pymt_amount'=>$row[0],$row[1],
'mode_of_pymt'=>$row[0],$row[1]));
}
echo json_encode(array("result"=>$r));
Which does not give me the expected result.How can I encode the data
in the right way? The following is the structure for the 2 tables
I am new to programming any help is appreciated.Thank you?
<?php
//Joining both tables on the basis of doc_no column
$sql = "SELECT billing_all.SUM(total_wt) AS total
,payment_details.pymt_amount
,payment_details.mode_of_pymt
FROM billing_all
,payment_details
WHERE billing_all.doc_no = payment_details.doc_no
AND billing_all.DATE = '15-Apr-2016'";
// Executing query
$res = mysqli_query($con,$sql);
//initializing array to store result
$rows = array();
//Iterating result and storing each row in $r then array $rows to covert result set into array because json accept array as parameter.
while($r = mysqli_fetch_assoc($res))
{
$rows[] = $r;
}
//print whole array in json format
echo json_encode($rows); ?>

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Categories