I'm trying to get, in result, one JSON string from a database of mine but the database returns multiple rows of data, that when JSON encoded, don't fit together with proper formatting.
My current PHP code
$conn = [omitted];
$sql = [omitted];
$result = $conn->query($sql); //this query has been proven to work
if ($result->num_rows > 0) {
$rows = [];
while($row = $result->fetch_assoc()) {
$row[] = array_merge($row,$rows);
}
echo json_encode($rows);
} else {
echo "0";
}
But this code echos the $rows array before it's been merged with the $row arrays.
Current Result:
[]
Wanted Result:
[{"id":"1","team_name":"[omitted]","has_finished":"0"},{"id":"2","team_name":"[omitted]","has_finished":"0"},{"id":"3","team_name":"[omitted]","has_finished":"0"},{"id":"4","team_name":"[omitted]","has_finished":"0"},{"id":"5","team_name":"[omitted]","has_finished":"0"},{"id":"6","team_name":"[omitted]","has_finished":"0"},{"id":"7","team_name":"[omitted]","has_finished":"0"}]
You are never assigning any data into your $rows array. To assign each row into the array you want this for your loop.
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
Related
I'm attempting to create a web app that displays records in my record collection stored in a database. I want to pull the rows from the database, convert them to JSON, then with Javascript write the JSON objects to an HTML page. Currently I have a php while loop writing the rows to an array..
<?php
include('./connection.php');
$query = "SELECT * FROM voting";
$result = $mysqli->query($query);
if (!$result) die($mysqli->error);
$array = array();
while ($row = $result->fetch_object()) {
$array[] = $row;
echo json_encode($array);
} ?>
The while loop is writing each row to it's own array. I want to place all of the returned JSON objects into one array. How do I achieve this?
php:
$array = array();
while ($row = $result->fetch_object()) {
$array[] = $row;
}
javascript:
<script>
var data = <?php echo json_encode($array, JSON_HEX_TAG); ?>;
</script>
console.log(data);
I have column name called as email. In that, I have more than 100 rows. Some rows have more than 10 records with a comma(,) some have only 1 records. I have to display all the records in one line.
This is my table
I am getting output like
The output I need in one line so that I can export it.
$sql ="SELECT email FROM email12";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$a=$row['email'];
$b = explode(',',$a);
echo '<pre>'; print_r($b);echo '<pre>';
}
}
I would iterate through exploded array:
$sql ="SELECT email FROM email12";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$a=$row['email'];
$b = explode(',',$a);
foreach($b as $email) {
echo '<pre>'; print_r($email);echo '<pre>';
}
}
}
From the database's perspective, it's not recommended and certainly not a good practice to have data as comma separated list. You should consider normalizing your database. Having said that, you should follow the below procedure to achieve the desired result as of now(or for the time being).
Create an empty array(for example, $resultArr) before the beginning of while loop. In each iteration of while loop, explode email column value and append them to $resultArr array. Finally, after coming out of the loop, simply perform implode operation on the resultant array to display all the records in one line.
$sql ="SELECT email FROM email12";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$resultArr = array();
while($row = $result->fetch_assoc()) {
$resultArr[] = explode(',',$row['email']);
}
echo implode(',', $resultArr);
}
What would the benefits be of storing db values into an array and then looping through the array vs just using a while loop?
Outputting db results to an array:
$records = array();
if($results = $db->query("SELECT name, address FROM town")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
}
Loop through array:
foreach($records as $r) {
$r->name;
}
VS a simple While loop:
if($result = $db->query("SELECT name, address FROM town")) {
if($count = $result->num_rows) {
while($row = $result->fetch_object()) {
echo $row->name, ' ', $row->address, '<br />';
}
$result->free();
}
}
Just a while loop and printing the result is easy and fast, but in certain times you want to do more then just print the array and then it becomes handy if you already work with arrays.
The most common use for this is freeing the resultset, allowing you to perform other db queries (updates, inserts...) before actually making any use of the results you got in the first place.
I have a few queries that I'm executing in my Android app. Each will only return one row of data, so I'd like to treat the output as JSONObjects rather than JSONArrays since they would be just be arrays with single objects inside; kind of pointless in my view.
As of now my PHP looks like this:
$query = "SELECT moveCount FROM Chessmates.Board_States WHERE Games_GameID = 2;";
$sth = mysqli_query($con, $query);
if(mysqli_errno()) {
echo "error";
} else {
$rows = array();
while($r = mysqli_fetch_array($sth, MYSQLI_ASSOC)) {
$rows[] = $r;
//var_dump($r);
}
echo json_encode($rows);
}
and the output looks like this:
[{"moveCount":"0"}]
I'd like it to look like this:
{"moveCount":"0"}
If it's only returning one row of data, then you don't need to make an array.
while($r = mysqli_fetch_array($sth, MYSQLI_ASSOC)) {
$rows = $r;
}
You get the data as you did because you were creating an array of objects, But since you're only going to ever get one result (as you stated), you can simple set it up as a variable.
I have a problem iterating through an sql query:
$result = mysql_query("SELECT * FROM transactions");
while($row = mysql_fetch_array($result)) {
// this returns 3 rows
foreach ($row as $values)
{
//fputcsv($a_csv, $values;
echo $values;
}
}
The script iterates fine but it appears to be going through each row twice. So what I receive in output is the following:
value1value1value2value2value3value3
I'm not sure why this is - could anyone explain please?
Thankyou
mysql_fetch_array fetches both the named & the numerical keys. Use either mysql_fetch_assoc or mysql_fetch_row.
$result = mysql_query("SELECT * FROM transactions");
//return an associative array
while($row = mysql_fetch_assoc($result)) {
// this returns 3 rows
$values = "{$row["name_of_column1"]}, {$row["name_of_column2"]}, {$row["name_of_column3"]}";
//fputcsv($a_csv, $values;
//print the whole row array
print_r($row);
//echo value in format value1, value2, value3
echo $values;
}
You need to access $row like this $row[0] And $row shouldn't be in a foreach() itself unless it too is some kind of array you need to iterate through.
$result = mysql_query("SELECT * FROM transactions");
while($row = mysql_fetch_row($result))
{
echo $row[0];
echo $row[1];
// ... etc.
}