Mysql tabella output in JSON

Jakub Lemiszewski

Utente Attivo
5 Dic 2013
119
1
0
Salve,
sto cercando di prendere una tabella MYSql e immetterla in jason in output a schermo.
Il codice seguente non mi fa nulla e non mi da errori e non capisco quale sia il problema:
PHP:
<?php
    //Create Database connection

$servername = "localhost";
$username   = "root";
$password   = "";
$dbname     = "demo";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
$conn or die(mysql_error());
    //Query.

$sql    = "SELECT * FROM countries";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));

    //Create an array

$json_response[] = array();

while ($row =mysqli_fetch_assoc($result)) {

    $row_array['code'] = $row['code'];

    $row_array['name_en'] = $row['name_en'];

    $row_array['name_fr'] = $row['name_fr'];

    //push the values in the array

    array_push($json_response,$row_array);

}
$jsonOtput = json_encode($json_response, JSON_PRETTY_PRINT);
echo $jsonOtput;

    //Close the database connection

$conn->close();

?>
Grazie per l'aiuto.
 
ho usato la stessa json array, a me funziona,
vedi di aver usato le "ASSOC" giuste
ciao
Marino

PHP:
$sql = "SELECT * FROM PERIODI WHERE id_periodo IN( ?, ?, ? ) and id_struttura=?";

print( "<br />-------------------- json array <br />" );
  $sth = $db->query( $sql, array( 11, 13, 15, 2 ) );

  $json_response = array(); 

  while( $row = $sth->fetch( PDO::FETCH_ASSOC ) ) {
    $json_response['id_periodo']	= $row['id_periodo']; 
    $json_response['id_struttura']	= $row['id_struttura']; 
    $json_response['data_inizio']	= $row['data_inizio']; 
    $json_response['data_fine']		= $row['data_fine']; 
  }
  $jsonOtput = json_encode($json_response, JSON_PRETTY_PRINT); 
  echo $jsonOtput."<br /><br />";

Codice:
-------------------- json array 
SELECT * FROM PERIODI WHERE id_periodo IN( 11, 13, 15 ) and id_struttura=2 

{ "id_periodo": "13", "id_struttura": "2", "data_inizio": "2014-04-15 00:00:00.000", "data_fine": "2014-04-30 00:00:00.000" }
 
Ultima modifica:
Grazie sono riuscito a farlo funzionare ma mi istituisce solo una riga e vorrei vedere tutto.
Mi sapresti dire come cambiare il codice per poter vedere tutto in json.
Grazie mille.
 

Discussioni simili