JSON encode MySQL results
Jak używać funkcji json_encode()
z wynikami zapytań MySQL? Czy muszę iterować wiersze, czy mogę po prostu zastosować go do całego obiektu wyników?
20 answers
$sth = mysqli_query("SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Funkcja json_encode
wymaga PHP > = 5.2 i pakietu php-json - Jak wspomniano tutaj
Uwaga: mysql
jest przestarzały od wersji PHP 5.5.0, użyj rozszerzenia mysqli
zamiast http://php.net/manual/en/migration55.deprecated.php .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:24
Spróbuj tego, to utworzy Twój obiekt poprawnie
$result = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['object_name'][] = $r;
}
print json_encode($rows);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-22 20:19:41
Http://www.php.net/mysql_query mówi "mysql_query()
zwraca zasób".
Http://www.php.net/json_encode mówi, że może zakodować dowolną wartość "z wyjątkiem zasobu".
Musisz iterować i zebrać wyniki bazy danych w tablicy, a następnie json_encode
tablicy.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-02 20:44:59
Dzięki to bardzo mi pomogło. Mój kod:
$sqldata = mysql_query("SELECT * FROM `$table`");
$rows = array();
while($r = mysql_fetch_assoc($sqldata)) {
$rows[] = $r;
}
echo json_encode($rows);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-24 10:16:36
Dzięki.. moja odpowiedź brzmi:
if ($result->num_rows > 0) {
# code...
$arr = [];
$inc = 0;
while ($row = $result->fetch_assoc()) {
# code...
$jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
$arr[$inc] = $jsonArrayObject;
$inc++;
}
$json_array = json_encode($arr);
echo $json_array;
}
else{
echo "0 results";
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-16 17:27:03
Powyższe nie zadziała, z mojego doświadczenia, zanim nazwiesz root-element w tablicy do czegoś, nie byłem w stanie uzyskać dostępu do niczego w ostatni json przed tym.
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows['root_name'] = $r;
}
print json_encode($rows);
To powinno wystarczyć!
Pär
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-11-15 13:19:53
Poniższy kod działa dobrze tutaj!
<?php
$con=mysqli_connect("localhost",$username,$password,databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "the query here";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-27 14:30:11
Moja prosta poprawka, aby nie umieszczać znaków mowy wokół wartości liczbowych...
while($r = mysql_fetch_assoc($rs)){
while($elm=each($r))
{
if(is_numeric($r[$elm["key"]])){
$r[$elm["key"]]=intval($r[$elm["key"]]);
}
}
$rows[] = $r;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-21 15:14:33
Przepraszam, to jest bardzo długo po pytaniu, ale:
$sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]")
AS json
FROM users;'
$msl = mysql_query($sql)
print($msl["json"]);
W zasadzie:
"SELECT" Select the rows
"CONCAT" Returns the string that results from concatenating (joining) all the arguments
"GROUP_CONCAT" Returns a string with concatenated non-NULL value from a group
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-30 21:17:57
Moglibyśmy uprościć Paolo Bergantino odpowiedź w ten sposób
$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-17 06:51:09
Jak utworzyć JSON przy użyciu danych z bazy danych MySQL
JSON (JavaScript Object Notation) jest obecnie bardziej preferowany niż XML, ponieważ jest lekki, czytelny i łatwy do zarządzania do wymiany danych na różnych platformach. zobaczymy jak można tworzyć dane JSON z tabeli pracowników przechowywanej w bazie danych MySQL.
echo json_encode($data);
Live: [Example ]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-30 07:36:50
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','dishant');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "select * from demo ";
$sth = mysqli_query($con,$sql);
$rows = array();
while($r = mysqli_fetch_array($sth,MYSQL_ASSOC)) {
$row_array['id'] = $r;
**array_push($rows,$row_array);**
}
echo json_encode($rows);
mysqli_close($con);
?>
Aarray_push ($rows,$row_array); pomoc w zbudowaniu tablicy w przeciwnym razie poda ostatnią wartość w pętli while
To działa jak append Metoda StringBuilder w java
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-19 07:48:03
Jeszcze jedna opcja użycia pętli FOR:
$sth = mysql_query("SELECT ...");
for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
print json_encode($rows);
Jedyną wadą jest to, że pętla for jest wolniejsza niż np. while lub szczególnie foreach
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-08 13:51:34
Na przykład $wynik = mysql_query ("SELECT * FROM userprofiles where NAME='TESTUSER'");
1.) jeżeli $result jest tylko jednym wierszem.
$response = mysql_fetch_array($result);
echo json_encode($response);
2.) jeżeli $wynik jest więcej niż jeden wiersz. Musisz iterować wiersze i zapisać je do tablicy i zwrócić json z tablicą w niej.
$rows = array();
if (mysql_num_rows($result) > 0) {
while($r = mysql_fetch_assoc($result)) {
$id = $r["USERID"]; //a column name (ex.ID) used to get a value of the single row at at time
$rows[$id] = $r; //save the fetched row and add it to the array.
}
}
echo json_encode($rows);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-17 05:31:23
Rozwiązałem TAK
$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
$list=array();
$i=0;
while ($cresult=$stmt->fetch()){
$list[$i][0]=$cde;
$list[$i][1]=$v_off;
$list[$i][2]=$em_nm;
$list[$i][3]=$q_id;
$list[$i][4]=$v_m;
$i=$i+1;
}
echo json_encode($list);
Zostanie to zwrócone do ajax jako zestaw wyników
i używając json parse w części javascript w ten sposób :
obj = JSON.parse(dataX);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-25 00:20:57
Mam takie same wymagania. Chcę tylko wydrukować obiekt wynikowy do formatu JSON, więc używam poniższego kodu. Mam nadzieję, że coś w nim znajdziesz.
// Code of Conversion
$query = "SELECT * FROM products;";
$result = mysqli_query($conn , $query);
if ($result) {
echo "</br>"."Results Found";
// Conversion of result object into JSON format
$rows = array();
while($temp = mysqli_fetch_assoc($result)) {
$rows[] = $temp;
}
echo "</br>" . json_encode($rows);
} else {
echo "No Results Found";
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-13 22:59:00
Kod:
$rows = array();
while($r = mysqli_fetch_array($result,MYSQL_ASSOC)) {
$row_array['result'] = $r;
array_push($rows,$row_array); // here we push every iteration to an array otherwise you will get only last iteration value
}
echo json_encode($rows);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-24 10:14:31
$rows = json_decode($mysql_result,true);
Takie proste: -)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-15 02:26:37
$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');
while($row = mysql_fetch_array($sql_results))
{
$subArray[location_id]=$row['location']; //location_id is key and $row['location'] is value which come fron database.
$subArray[x]=$row['x'];
$subArray[y]=$row['y'];
$array[] = $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-23 09:42:58
Sprawdź poniższy kod pod kątem użycia mysql_fetch i json_encode. Będziesz musiał iterować przez wiersze, ale jeśli używasz mysqli sytuacja ulegnie zmianie
$kt_query="SELECT * FROM tbl_xxx";
$kt_result = mysql_query($kt_query) or die('Query failed: ' . mysql_error());
$rows= array();
while($sonuc=mysql_fetch_assoc($kt_result))
{
$rows[]=$sonuc;
}
print json_encode($rows);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-21 10:39:21