Export information from MYSQL to JSON

0

Sorry for ignorance, I do not understand anything about JSON.

I have a website with database in MYSQL that the client needs to export to JSON to integrate with an app.

Can you give me a light on where to start?

Ex: table with information: name, email, id

Thank you!

    
asked by anonymous 19.07.2017 / 20:54

4 answers

1

To create the contents of a JSON file, first we create a array :

$meus_dados = array();

Once we have a array created we should array :

for ($i = 0; $i < 3; $i++) {
    $meus_dados[$i]['nome'] = "nome".($i + 1);
    $meus_dados[$i]['email'] = "email".($i + 1);
    $meus_dados[$i]['id'] = "id".($i + 1);
}

Now that we already have our array populated, we have to use the json_encode function to generate a JSON of that array :

echo json_encode($meus_dados);

Result

  

[{"name": "name1", "email": "email1", "id": "id1"},
  {"name": "name2", "email": "email2", "id": "id2"},
  {"name": "name3", "email": "email3", "id": "id3"}]

    
19.07.2017 / 21:06
2

You can work as follows using PHP:

$query = "SELECT * FROM 'table'";
$stmt->prepare($query);
$stmt->execute();
$stmt->fetchAll(\PDO::FETCH_ASSOC);

if($stmt){
    echo json_encode(["status"=>true,"msg"=>"Json enviado com sucesso!","data"=>$stmt]);exit;
}else{
    echo json_encode(["status"=>false,"msg"=>"Ocorreu um erro"]);exit;
}
    
19.07.2017 / 21:17
1

JSON ( link ) is a data format. It facilitates the exchange of data between different systems, as it is simple to generate and retrieve. For your case, you need to generate an output in JSON for it to be read by the system.

Retrieve the data the same way you would for any application. The difference will be in the output (or screen display), which will have the application/json format. In the simplest way possible:

$data = mysql_query('select * from table'); // aplique o seu metodo de recuperacao de dados
header('Content-type: application/json'); // cabecalho para o navegador saber que estah retornando um json
echo json_encode($data); // json_encode transforma qualquer tipo de objeto no formato json
exit;
    
19.07.2017 / 21:09
0

If you are using PDO you can make your return very elegant:

public function getCliente ( $idcliente ){
        require_once "class.connection.php";
        require_once "../model/class.cliente.php";
        $retorno = array();
        $this->connection = new connection();

        try{
            $query = "SELECT * FROM cliente WHERE CD_CLIENTE = :cliente";
            $stmt = $this->connection->prepare( $query );
            $stmt->bindValue( ":cliente", $idcliente, PDO::PARAM_INT );
            $stmt->execute();

            if( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
                $retorno = array(
                   "id"    =>  $row['CD_CLIENTE'] ,
                   "nome"  =>  $row['NM_CLIENTE'] ,
                   "email" =>  $row['DS_EMAIL']
                )
            }

            $this->connection = null;
        }catch (PDOException $ex){
            echo "Erro: ".$ex->getMessage();
        }
        echo json_encode(array("cliente" => $retorno));
    }

The return will look something like this:

{
  "cliente" : [{
              "id"    : "1",
              "nome"  : "Leandro",
              "email" : "[email protected]"
              }]
}
    
20.07.2017 / 03:17