Json does not return data from the Mysql database

0

I have a table in the Mysql database that contains 3 fields (id, name and model) different from the other fields, the data email template with tags HTML (structure in longtext ).

When I run the PHP code to return the data to me, it does not return any information. when I run the same script on another table, the data is returned perfectly. I believe it's the data with tags HTML that exists in my my template.

Below is all my script PHP :

    <?php

include_once "conexao.php";

$sql = $db->prepare("SELECT * FROM modelo_email");          
$sql->execute();
while($data = $sql->fetchAll( PDO::FETCH_ASSOC )){
    $json ["data"] = $data;

}

 echo json_encode($json);
    
asked by anonymous 01.07.2018 / 20:13

2 answers

1

In select you are not informing the field names of the table you want to play in the array.

$sql = $db->prepare("select id, descricao, modelo_email from modelo_email");

Here you should use fetch and not fetchAll because in while you are expecting to fetch one information at a time and fetchAll brings an array of

while($data = $sql->fetch(PDO::FETCH_ASSOC)){

You can use fetchAll but in this case I recommend using foreach.

In this last part you are wanting to give an echo out while and that is why it is returning null. If you give the echo within the while it will display correctly

while($data = $sql->fetch(PDO::FETCH_ASSOC)){
       {
             echo $json = $data['descricao'];
             // var_dump($json);
        }

I do not understand much of php, but giving a searched on the internet, if you want to display the result of the while out of it, you can declare a variable as global.

foreach($data = $sql->fetchAll(PDO::FETCH_ASSOC) as $data1)
    {
         $_global= $json = $data1['descricao'];
         // var_dump($json);
    }
       echo $json;

More like I said, I do not understand almost anything about PHP, I've only been in this project for 10 days, so I advise you to take a look at global variables before using them.

    
02.07.2018 / 00:19
1

It is because you have inverted the positions when storing the information in the variable.

 <?php

include_once "conexao.php";

$sql = $db->prepare("SELECT * FROM modelo_email");          
$sql->execute();
while($data = $sql->fetchAll( PDO::FETCH_ASSOC )){

   //Abaixo você cria a variável e armazena o conteúdo do array nela; 
   $json = $data["data"];

}

 echo json_encode($json);
    
01.07.2018 / 20:52