I have a mysql database of countries, 250 in total, which in want to give over to an Android app. I know i have to use php in between to parse the result into JSON. This is it:
<?php
require_once('connection.php');
$response = array();
$resultarray = array();
$result = mysqli_query($con, "SELECT * FROM countries");
if (!empty($result)) {
// check for empty result
while ($row=mysqli_fetch_assoc($result)) {
print $row;
$resultarray = mysqli_fetch_array($result);
$Laender = array();
$Countries[de] = $resultarray["de"];
$response["Countries"] = array();
array_push($response["Countries"], $Countries);
echo json_encode($response);
}
}
?>
I ran the script in my browser and it displays correctly, except that half the countries are missing. There are only 125 countries displayed. Where have they vanished to?
Both functions mysqli_fetch_assoc and mysqli_fetch_array do the same - they fetch next record.
So, in your while you fetch first record with mysqli_fetch_assoc and then immediately fetch second record with mysqli_fetch_array. So, the first record is lost. And this happens on every iteration, so half of your records are lost.
Get rid of mysqli_fetch_array call:
$response["Countries"] = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($response["Countries"], $row["de"]);
}
echo json_encode($response);
Related
here is my problem.
function getSent($id) {
include 'dbh.php';
$data = array();
$sql = "SELECT * from message WHERE senderid='$id'";
$result = $con->query($sql);
$row = $result->fetch_assoc();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
In the theory this method is picking all messages (in this case), but it always find one message less than in the db => If I drop the whole table, I will get an array with the size of 0.
How could I fix this?
Remove the first $row = $result->fetch_assoc();. You are fetching one row, then looping to fetch the rest of the data and you don't store the first fetch.
`
I want to give some data from a MySQL database to a Android App via JSON.
So far i have written this php script to give me the JSON object:
$result = mysqli_query($con,"SELECT * FROM job");
$row = mysqli_fetch_assoc($result);
while($row = mysqli_fetch_assoc($result)){
$output[] = $row;
}
print(json_encode($output));
I have found out by accident that when I dont add the line "$row = mysqli_fetch_assoc($result);" before the while-loop it doesn`t return anything. But when I do add this line like in the example the JSON object doesnt contain the first element.
I believe its because of this line where $row already contains the first line.
Hopefully you can help me :)
With purpose to figure out what wrong with your query you have to do something like this:
if ($result = mysqli_query($db, $sql)) {
// Here you can see and check count of rows in your result set.
$numRows = mysqli_num_rows($result);
// ...
} else {
// Here you can see and check and understand error.
var_export(mysqli_error($db));
}
with purpose to traverse all your rows from result set you have to do:
while ($row = mysqli_fetch_assoc($result)) {
var_export($row);
}
and you must not have $row = mysqli_fetch_assoc($result) before while loop.
What's the best way to output all results from a SELECT query?
if ($result = mysqli_query($con, "SELECT name,pic_url FROM accounts")) {
$data = mysqli_fetch_assoc($result);
var_dump($data);
mysqli_free_result($result);
}
At present dumping of $data only outputs one result, even though a quick check of mysqli_num_rows() shows two results (and there are two rows in the table).
What's the best way to output this data?
I'm essentially looking to output the name field and the pic_url for each row so I was hoping to receive my results as an array which I can then loop through using foreach
you need to use a loop.
while ($data = mysqli_fetch_assoc($result)) {
var_dump($data);
}
Use simple while loop and store in an array:
if ($result = mysqli_query($con, "SELECT name,pic_url FROM accounts"))
{
while ($data[] = mysqli_fetch_assoc($result));
}
I've got a database with 5 columns and multiple rows. I want to fetch the first 3 rows and echo them as an array. So far I can only get the first row (I'm new to PHP and mysql). Here's my PHP so far:
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
//==== ECHO AS JSON
echo json_encode($array);
Help would be much appreciated.
You need to loop through the results. mysql_fetch_row gets them one at a time.
http://php.net/manual/en/function.mysql-fetch-row.php
The code would end up like:
$jsonData = array();
while ($array = mysql_fetch_row($result)) {
$jsonData[] = $array;
}
echo json_encode($jsonData);
//json_encode()
PLEASE NOTE
The mysql extension is deprecated in PHP 5.5, as stated in the comments you should use mysqli or PDO. You would just substitute mysqli_fetch_row in the code above.
http://www.php.net/manual/en/mysqli-result.fetch-row.php
I do like this while quering an ODBC database connection with PHP 5.5.7, the results will be in JSON format:
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
Fetching results allowing edit on fields:
while( $row = odbc_fetch_array($result) ) {
$json['field_1'] = $row['field_1'];
$json['field_2'] = $row['field_2'];
$json['field_3'] = $row['field_1'] + $row['field_2'];
array_push($response, $json);
}
Or if i do not want to change anything i could simplify like this:
while ($array = odbc_fetch_array($result)) { $response[] = $array; }
What if i want to return the results in JSON format?, easy:
echo json_encode($response, true);
You can change odbc_fetch_array for mysqli_fetch_array to query a MySql db.
According to the PHP Documentation mysql_fetch_row (besides that it's deprecated and you should use mysqli or PDO)
Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
so you need for example a while loop to fetch all rows:
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row;
}
echo json_encode($rows);
I leave it to you how to only fetch 3 rows :)
You need to put this in some kind of a loop, mysql_fetch_row returns results one at a time.
See example:
http://www.php.net/manual/en/mysqli-result.fetch-row.php#example-1794
$result = mysql_query( "SELECT * FROM $tableName ORDER BY id LIMIT 3");
$json = array();
while($array = mysql_fetch_row($result)){
$json[] = $array;
}
echo json_encode($json);
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