Create a Json array in a for loop - php - php

<?php
include '../connection.php';
$sql="SELECT userid,name,batch FROM dbusers";
$results=mysql_query($sql) or die("Cannot execute query");
$count=mysql_num_rows($results);
$arr=array();
for($i=0; $i < $count; $i++){
$rows=mysql_fetch_array($results);
//What to put here ?
}
json_encode($arr);
?>
This is my php code. I want to ask what to put inside the for loop so that I can create a an array of array in php. The inner array will have userid, name and batch as its elements .

What to put here ?
$arr[] = $rows;
Full code
<?php
include '../connection.php';
$sql="SELECT userid,name,batch FROM dbusers";
$results=mysql_query($sql) or die("Cannot execute query");
$count=mysql_num_rows($results);
$arr=array();
for($i=0; $i < $count; $i++){
$rows=mysql_fetch_array($results, MYSQL_ASSOC);//use MYSQL_ASSOC so you wouldn't have duplicate data
$arr[] = $rows;
}
$json = json_encode($arr);
?>

<?php
include '../connection.php';
$sql = "SELECT userid,name,batch FROM dbusers";
$results = mysql_query($sql) or die("Cannot execute query");
$arr = array();
while($rows = mysql_fetch_assoc($results)){
$arr[] = $row;
}
echo json_encode($arr);
?>
try this.

Related

MySQL Query Returns 0 When Running Multirowed Response Query

When I run the following code In PHP
$connect = mysqli_connect("localhost", "root", "dbpass", "db");
function csvfromarray($array) {
$result = $array[0]+","+$array[1];
return $result;
}
$query = mysqli_query($connect, "SELECT * FROM dbtable");
$row = mysqli_fetch_assoc($query);
$data = array();
$i = 0;
while($row = mysqli_fetch_assoc($query)) {
$data[$i] = $row['last'];
$i++;
}
$csv = csvfromarray($data);
echo $csv;
mysqli_close();
I end up getting an echoed response of "0" when I should be returning "lname1,lname2".
All of chris85's stuff is correct...
Here's a tidy up:
$query=mysqli_query($connect,"SELECT `last` FROM dbtable");
$data=array();
while($row=mysqli_fetch_assoc($query)) {
$data[]=$row['last']; // push into array
}
echo implode(',',$data); // echo comma-separated values
mysqli_close();

php and mysql issue with query return

I have this code working but only halfway, it is able to return all of the information that I need however on the return, one of the JSON array is returned twice, why is this? I can't seem to figure out why.
Here is my code:
$rows = mysql_num_rows($res);
$array = array();
$i = 0;
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$array[$i] = (int)$row[0] . "\n";
$i++;
if ($i > $rows){
break;
}
}
$JsonArray = array();
for($i = 0; $i < $rows; $i++){
$q = "SELECT firstName, lastName, email from $mysql_database.$UsersTable WHERE idUser = $array[$i]";
$res = mysql_query($q, $connect) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$new_array[] = $row; // Inside while loop
}
$JsonArray[$i] = $new_array;
}
echo json_encode($JsonArray);
This is the result:
All I need is the second and third but somehow I don't know why it is outputting the first twice.
Also, how can I format the result better in the JsonArray?
From what I see you are trying to do, you are trying to fetch your result set from the database for the query.
You need not make use of all those loops. All you have to do is:
$q = "SELECT firstName,lastName,email from $mysql_database.$UsersTable WHERE idUser=$array[$i]";
$res = mysql_query($q,$connect) or die(mysql_error());
$new_array = mysqli_fetch_assoc($res);
mysqli_free_result($res);
You do not need that while loop for each row.

PHP JSON Array encoding for use with JSOUP Android

I am trying to build a catalog database that will interact with an Android Application for viewing when one scans a barcode. The app should ask the MySQL database and query for the various items associated with the part. Code is here for the MySQL part of it:
<?php
if(isset($_POST['submit']) || isset($_POST['catalog'])) {
require("connect_to_mysql.php");
header("content-type: application/json");
$tables_result = mysql_query("SHOW TABLES") or die(mysql_error());
while ($table = mysql_fetch_row($tables_result)) {
$query_results = mysql_query("SELECT * FROM ".$table[0]." WHERE catalog = '".$_POST['catalog']."'") or die(mysql_error());
if (mysql_num_rows($query_results) > 0) {
$fields = mysql_query("SHOW COLUMNS FROM ".$table[0]);
while ($res = mysql_fetch_array($fields)) {
$names[] = $res[0];
}
$comments = mysql_fetch_row(mysql_query("SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_name='".$table[0]."'")) or die(mysql_error());
while($array = mysql_fetch_array($query_results)){
$rows["part"] = $comments[0];
$rows["fields"] = $names;
for($i = 0; $i < mysql_num_fields($query_results); $i++){
$rows[$names[$i]] = $array[$i];
}
echo json_encode($rows);
}
}
}
mysql_free_result($tables_result);
}
if(!isset($_POST['submit']) || !isset($_POST['catalog'])) {
echo "
<form method='post'>
<input type='text' name='catalog' />
<input type='submit' name='submit' />
</form>
";
}
?>
However, for instance, a result of this would be:
{"part":"Lospa Tibial Baseplate","fields":["catalog","size"],"catalog":"01.10.50B","size":"11"}
I am using JSOUP on the Android Client Side and it has the function of returning a JSONArray. A JSONArray from when I've used this in the past looks like this (the part of the JSON I am having a problem with is the "field" object):
{"part":"Lospa Tibial Baseplate","fields":{["catalog","size"]},"catalog":"01.10.50B","size":"11"}
I've tried straight up encoding the array before encoding the fields array but that didn't work out and returned a bunch of slashes and useless stuff:
{"part":"Lospa Tibial Baseplate","fields":"[\"catalog\",\"size\"]","catalog":"01.10.50B","size":"11"}
What's the best way I should go about this? I would rather not just hard-code the two brackets into there, but if that is the last option, please show me how to do that because I can't just $rows["fields"] = "{".$names."}";
Try encoding the structure after it has finished building:
if(isset($_POST['submit']) || isset($_POST['catalog'])) {
require("connect_to_mysql.php");
header("content-type: application/json");
$tables_result = mysql_query("SHOW TABLES") or die(mysql_error());
while ($table = mysql_fetch_row($tables_result)) {
$query_results = mysql_query("SELECT * FROM ".$table[0]." WHERE catalog = '".$_POST['catalog']."'") or die(mysql_error());
if (mysql_num_rows($query_results) > 0) {
$fields = mysql_query("SHOW COLUMNS FROM ".$table[0]);
while ($res = mysql_fetch_array($fields)) {
$names[] = $res[0];
}
$comments = mysql_fetch_row(mysql_query("SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_name='".$table[0]."'")) or die(mysql_error());
while($array = mysql_fetch_array($query_results)){
$rows["part"] = $comments[0];
$rows["fields"] = $names;
for($i = 0; $i < mysql_num_fields($query_results); $i++){
$rows[$names[$i]] = $array[$i];
}
}
// JSON encode at the end
echo json_encode($rows);
}
}
mysql_free_result($tables_result);
}
This is invalid JSON, by the way:
{"fields":{["catalog","size"]},"catalog":"01.10.50B","size":"11"}
Should be more like this if fields must be an object.
{"fields":{"key":["catalog","size"]},"catalog":"01.10.50B","size":"11"}
So it's better to check if your JSOUP parsing is setup correctly.
I figured it out. Here is my code below. I basically had to make an array of encoded JSON objects. Thanks to Kim for pointing in the right direction. I also did some changes the the function, but that doesn't have an impact on the JSON Part of it.
<?php
if(isset($_POST['catalog'])) {
require("connect_to_mysql.php");
header("content-type: application/json");
$tables_result = mysql_query("SHOW TABLES") or die(mysql_error());
while ($table = mysql_fetch_row($tables_result)) {
$query_results = mysql_query("SELECT * FROM ".$table[0]." WHERE catalog = '".$_POST['catalog']."'") or die(mysql_error());
if (mysql_num_rows($query_results) > 0) {
$comments = mysql_fetch_row(mysql_query("SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_name='".$table[0]."'")) or die(mysql_error());
$columns_sql = mysql_query("SELECT COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_NAME = '".$table[0]."'") or die(mysql_error());
$rows["validity"] = true;
$rows["part"] = $comments[0];
while ($res = mysql_fetch_array($columns_sql)) {
$names[] = $res[0];
}
$rows["fields_count"] = count($names);
while($array = mysql_fetch_array($query_results)){
for($i = 0; $i < mysql_num_fields($query_results); $i++){
$values[] = array($names[$i] => $array[$i]);
}
}
$rows["fields"] = $values;
echo json_encode($rows);
exit();
}
}
echo '{"validity":false}';
mysql_free_result($tables_result);
}
?>
The field structure is not correct...
This is why I use the Simple JSON for PHP library! It allows to avoid to hardcode our JSON.
Using $Json->addContent(new arrayJson("fields",$values)); will set the field fields of your json equals to your values. It should look like this :
<?php
include('includes/json.php');
$Json = new json();
if(isset($_POST['catalog'])) {
require("connect_to_mysql.php");
header("content-type: application/json");
$tables_result = mysql_query("SHOW TABLES") or die(mysql_error());
while ($table = mysql_fetch_row($tables_result)) {
$query_results = mysql_query("SELECT * FROM ".$table[0]." WHERE catalog = '".$_POST['catalog']."'") or die(mysql_error());
if (mysql_num_rows($query_results) > 0) {
$comments = mysql_fetch_row(mysql_query("SELECT table_comment FROM INFORMATION_SCHEMA.TABLES WHERE table_name='".$table[0]."'")) or die(mysql_error());
$columns_sql = mysql_query("SELECT COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_NAME = '".$table[0]."'") or die(mysql_error());
$Json->addContent(new propertyJson('status', '200'));
$Json->addContent(new propertyJson('validity', true));
$Json->addContent(new propertyJson('part', $comments[0]));
while ($res = mysql_fetch_array($columns_sql)) {
$names[] = $res[0];
}
$Json->addContent(new propertyJson('count', count($names))); =
while($array = mysql_fetch_array($query_results)){
for($i = 0; $i < mysql_num_fields($query_results); $i++){
$values[] = array($names[$i] => $array[$i]);
}
}
$Json->addContent(new arrayJson("fields",$values));
json_send($Json);
exit();
}
}
$Json->addContent(new propertyJson('status', '200'));
$Json->addContent(new propertyJson('message', 'Validity failed'));
json_send($Json);
mysql_free_result($tables_result);
}
?>

Fetching from mysql and storing in an array in php?

$query= "Select * from std";
$res= mysqli_query($con, $query);
$idArray=array();
$i=0;
while ($row = mysqli_fetch_array($res)) {
$idArray[$i]=htmlentities($row["id"]);
$i++;
}
for($j=0;$j<=$i;$j++){
echo $idArray[j]."asd<br>";
}
In output it shows only "asd" 5 times as i have five records but i does not showing the id's of those records,
Thanks in advance,
You're missing a dollar sign on the echo-row:
echo $idArray[j]."asd<br>";
Should be
echo $idArray[$j]."asd<br>";
try this
$query= "Select * from std";
$res= mysqli_query($con, $query);
$idArray=array();
while ($row = mysqli_fetch_array($res)) {
$idArray[] =htmlentities($row["id"]);
}
for($j=0;$j<sizeof($idArray);$j++){
echo $idArray[$j]."asd<br>";
}
You have to get count of $idArray and pass it to for loop
for($j=0;$j<count($idArray);$j++){
echo $idArray[$j]."asd<br>";
}
But why are you using different for loop .... you could echo in while loop.
<?php
$db = mysql_connect('localhost','root','');
mysql_select_db('test_db',$db);
$data = array();
$query = mysql_query("SELECT * FROM test_table");
while($row = mysql_fetch_object($query) ) {
$data[] = $row;
}
print_r($data);
?>
Example Taken From :
http://arjun.net.in/displaying-mysql-table-records-in-unordered-list-format-using-php/

Reading only one row from mysql when there are two

I need the script to output both rows. However, I can only get it to output the first one. Help please!
Here is my code:
<?php
$server = ""; // assume server name
$connect = mysqli_connect($server,,,) //assume password etc.
or die ("Couldn't connect to server"); //connect to admin database
$query = "SELECT mt FROM Content";
$result = mysqli_query($connect, $query)
or die ('Could not execute query.');
$nrows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$i = 0;
while ($i <= 30)
{
echo $row[$i];
$i++;
}
?>
You need to fetch into a row in a loop:
while ($row = mysqli_fetch_array($result)) { ...
Try to type:
while( $row = mysqli_fetch_array($result) )
{
echo $row[$i];
$i++;
}
You only fetch the first row.
You should do a while loop on your mysqli_fetch_array() to get both rows.
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < 30; $i++) {
echo $row[$i];
}
}
That should do it (like some of the other posted while I was writing but they forgot parts of the answer :-)
But I think that you should use the OO way of using mysqli.
You could use mysqli_fetch_all() to fetch all of the records.

Categories