Resultados de JSON encode MySQL


¿Cómo uso la función json_encode() con los resultados de la consulta MySQL? ¿Necesito iterar a través de las filas o puedo simplemente aplicarlo a todo el objeto results?

 278
Author: Gottlieb Notschnabel, 2008-12-20

20 answers

$sth = mysqli_query("SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

La función json_encode necesita PHP > = 5.2 y el paquete php-json - como se menciona aquí

NOTA: mysql está obsoleto a partir de PHP 5.5.0, use mysqli extensión en lugar http://php.net/manual/en/migration55.deprecated.php .

 459
Author: Paolo Bergantino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:24

Prueba esto, esto creará tu objeto correctamente

 $result = mysql_query("SELECT ...");
 $rows = array();
   while($r = mysql_fetch_assoc($result)) {
     $rows['object_name'][] = $r;
   }

 print json_encode($rows);
 40
Author: ddavtian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-22 20:19:41

Http://www.php.net/mysql_query dice: "mysql_query() devuelve un recurso".

Http://www.php.net/json_encode dice que puede codificar cualquier valor "excepto un recurso".

Necesita iterar y recopilar los resultados de la base de datos en una matriz, luego json_encode la matriz.

 24
Author: Hugh Bothwell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-02 20:44:59

Gracias esto me ayudó mucho. Mi código:

$sqldata = mysql_query("SELECT * FROM `$table`");

$rows = array();
while($r = mysql_fetch_assoc($sqldata)) {
  $rows[] = $r;
}

echo json_encode($rows);
 15
Author: Tokes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-24 10:16:36

Gracias.. mi respuesta es:

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";
        }
 8
Author: aashima,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-16 17:27:03

Lo anterior no funcionará, en mi experiencia, antes de nombrar el elemento raíz en la matriz a algo, no he sido capaz de acceder a nada en el json final antes de eso.

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows['root_name'] = $r;
}
print json_encode($rows);

¡Eso debería hacer el truco!

Pär

 7
Author: Pär,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-15 13:19:53

El siguiente código funciona bien aquí!

<?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);
?>
 6
Author: ferreirabraga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-27 14:30:11

Mi solución simple para evitar que ponga marcas de voz alrededor de valores numéricos...

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;
}   
 3
Author: James,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-21 15:14:33

Lo siento, esto es extremadamente largo después de la pregunta, pero:

$sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]") 
AS json 
FROM users;'
$msl = mysql_query($sql)
print($msl["json"]);

Básicamente:

"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
 3
Author: gear4,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-30 21:17:57

Podríamos simplificar Paolo Bergantino responder así

$sth = mysql_query("SELECT ...");
print json_encode(mysql_fetch_assoc($sth));
 2
Author: jrran90,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-17 06:51:09

Cómo crear JSON usando datos de la base de datos MySQL

JSON (JavaScript Object Notation) es más preferido hoy en día sobre XML, ya que es ligero, legible y fácilmente manejable para el intercambio de datos a través de varias plataformas. veremos cómo se pueden crear datos JSON a partir de la tabla de empleados almacenada en la base de datos MySQL.

 echo json_encode($data);

En Vivo : [Ejemplo ]

 2
Author: indian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
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 rows, row row_array); ayuda a construir el array de lo contrario da el último valor en el bucle while

Este trabajo como anexar método de StringBuilder{[3] {} en[2]}java

 2
Author: DishantPatel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-19 07:48:03

Una opción más usando el bucle FOR:

 $sth = mysql_query("SELECT ...");
 for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
 print json_encode($rows);

La única desventaja es que el bucle for es más lento que, por ejemplo, while o especialmente foreach

 1
Author: NGix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-08 13:51:34

Por ejemplo result result = mysql_query ("SELECT * FROM userprofiles where NAME='TESTUSER'");

1.) si result result es solo una fila.

$response = mysql_fetch_array($result);
echo json_encode($response);

2.) si result result es más de una fila. Debe iterar las filas y guardarlas en una matriz y devolver un json con una matriz.

$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);
 1
Author: Jyoti Prakash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-17 05:31:23

Resolví así

$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);		
Esto será devuelto a ajax como conjunto de resultados y mediante el uso de json parse en javascript parte como esta :

obj = JSON.parse(dataX);
 1
Author: Bineesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-25 00:20:57

Tengo el mismo requisito. Solo quiero imprimir un objeto de resultado en formato JSON, así que uso el código a continuación. Espero que encuentres algo en él.

// 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";
}
 1
Author: Darshan Dhoriya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-13 22:59:00

Código:

$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);
 1
Author: inrsaurabh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-24 10:14:31
$rows = json_decode($mysql_result,true);

Tan simple como eso: -)

 0
Author: AMG Sistemas y Desarrollo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
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).'}';
 0
Author: Bijender Singh Shekhawat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-23 09:42:58

Compruebe el siguiente código para usar mysql_fetch y json_encode. Tendrá que iterar a través de las filas, pero si utiliza mysqli la situación cambiará

$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);
 0
Author: user3172285,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-21 10:39:21