Create Json for PHP based on Mysql

Asked

Viewed 3,070 times

1

I wonder if anyone finds any error in my code because I’m trying to create a Json with PHP but it only returns NULL.

My Host server uses PHP 5.6

 <?PHP    
    $host = "...";    
    $usuario = "...";    
    $senha = "...";    
    $banco = "...";    

    $database = mysqli_connect($host,$usuario,$senha,$banco);    

$result=mysqli_query("SELECT * FROM tbconsultas");

$i=0;
while($row=mysqli_fetch_array($result)) { 
  $response[$i]['url']  = $row['url']; 
  $response[$i]['title']= $row['title'];
  $data['posts'][$i] = $response[$i];
  $i=$i+1;
} 

$json_string = json_encode($data);

$file = 'file.json';
file_put_contents($file, $json_string);
?> 
  • 1
  • @Marceloboni I tried to use 'mysqli' but created Null the same way

  • Never use the mysql extension, the extension is obsolete and no longer works from php 7

  • I am using php 5.6 on my @Marceloboni server

  • put at the beginning of your code error_reporting(E_ALL); See if she gave a message and put it here to help.

  • First of all, change the extension to mysqli ;] It is not because your server still supports the extension, that it should still be used

  • I switched to the mysqli however I did not succeed in creating Json @Marceloboni

  • What returns null? Perform a var_dump( json_last_error_msg()); and check if there is an error (and which is it) in json_encode. See if the database is in UTF8 as well.

  • @Inkeliz the null is the Json I get after creating it with php. and var_dump I should put it where ?

  • Place at the end of the code. The json_last_error_msg() will return the code of the last error that occurred on json_encode().

  • @Inkeliz string(8) "No error" that was the mistake I received

  • @Matheusrohwedder, you put the json_last_error() after the call of json_encode()? This could be something with UTF8 since it’s picking up Urls and titles.

  • @Fernandobagno yes it was after the json_encode() I’ll have to take a look but I think this in utf-8 yes

  • It would be nice to see what your base has, because your code ran here for me quietly using a base of mine.

  • @Fernandobagno by what I saw my phpmyadmin is using utf8mb4_unicode_ci

  • @Fernandobagno do not know what happened but mysteriously worked

  • Have you changed the Internet? Are you using UTF8? Ideally your bank is in Utf8_general_c

  • @Fernandobagno I implemented Anderson’s code below and it worked now

Show 13 more comments

1 answer

3


I don’t have PHP lower than 7 on my machine, so I can’t test your code to tell you punctually what the error is, but using Mysqli you can do something like:

// Conecta com o banco de dados:
$mysqli = mysqli_connect("localhost", "root", "", "sopt");

// Seleciona todos os registros da tabela:
$result = mysqli_query($mysqli, "SELECT * FROM tbconsultas");

// Retorna todos os registros:
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);

// Escreve o resultado JSON em arquivo:
file_put_contents("file.json", json_encode($data));

If it is not possible to use the function mysqli_fetch_all as shown above, just make a repeat loop iterating over all the records and storing in a array.

// Lista que armazenará todos os registros:
$rows = [];

// Percorre todos os registros:
while ($row = mysqli_fetch_assoc($result)) {

    // Adiciona o registro na lista:
    array_push($rows, $row);

}

At the end, just convert the list to JSON:

$json = json_encode($rows);
  • Anderson, I tried to use the functions mysqli which showed above but did not succeed

  • @Matheusrohwedder then probably the error is not in the Mysql calls, but in your repetition loop which is very confusing. I tested the above code and it works perfectly. You don’t need the loop, just use the function mysqli_fetch_all.

  • When trying to use mysqli_fetch_all I can’t even run the file through the browser

  • @Matheusrohwedder Why not? What error appears? Please give details! Can you post your code to http://ideone.com and send the link? How many records are there in the table? It’s giving timeout?

  • The code I’m using is what was posted in the question, I put your code in place of mine, just putting my connection to db, ha 1 row of records in the table for test, porem has 8 columns.

  • error while using your Cod meusite.com.br não consegue atender a esta solicitação no momento.&#xA;HTTP ERROR 500

  • If the code is the same as mine, it should work. Please post your code in Ideone and send the link. You’ve probably done something wrong and you’re not noticing it. For example, in function mysqli_query you passed the connection parameter?

  • http://ideone.com/1HC8wQ with its code

  • To use the mysqli_fetch_all needs the mysqlnd.

  • but there to use the mysqlnd would I have to change a lot of things? @Inkeliz

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.