Error generating field for JSON from PHP

-1

I'm trying to pass a news list by JSON from PHP

<?php
...
$sql = $conn->prepare('SELECT * FROM noticias');
$sql->execute();

while($row = $sql->fetch()) {
  $data['titulo'] .= " ".$row->titulo." ";    
}

echo json_encode($data);   
exit();
?>

The problem is that as a result it brings me this: {"titulo":" "} and not the list of news titles. I do not know what I'm doing wrong.

    
asked by Alvaro Montoro 12.04.2018 в 17:18
source

7 answers

1

See if this is useful for you:

$dataTitulos = array();
while($row = $sql->fetch())
{
    array_push($dataTitulos, $row->titulo);
}
$data['titulo'] = $dataTitulos;

echo json_encode($data);
exit();
    
answered by 12.04.2018 / 17:24
source
1

test specifying the type of fetch

 $connSTR = "mysql:host=".$db['hostname'].";dbname=".$db['database'].";charset=utf8mb4";
 $conn = null;
 try {
     $conn = new PDO($connSTR, $db['username'], $db['password']);
     // set the PDO error mode to exception
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     // echo ("Connected successfully ".PHP_EOL);
 }
 catch(PDOException $e)
     {
     // echo ("Connection failed: ". $e->getMessage().PHP_EOL);
      }
 $result = "";
 $sql = "SELECT * FROM noticias WHERE 1";
 $sth = $conn->prepare($sql);
 $sth->execute() or die($sth->errorInfo());
 while ($row = $sth->fetch(PDO::FETCH_ASSOC)) :
      $result .= $row['titulo']." ";
 endwhile;

 $data = array("titulo"=>$result);
 echo json_encode($data);
 exit();

I use PDO::FETCH_ASSOC by habit (and I agree to $row['columna']; ) in your case it would be PDO::FETCH_OBJ to access by $row->columna

    
answered by 12.04.2018 в 17:45
1

<?php
...
$sql = $conn->prepare('SELECT * FROM noticias');
$sql->execute();
$sql->fetchAll(PDO::FETCH_ASSOC);

//Si hay registros nuestra variable $results seria igual a lo que obtengamos del query, si no contendrá un warning de que no hay registros obtenidos por la consulta.

$results = (count($sql) > 0) ? $sql : array("error"=>"No hay opciones en la BD");

//Lo convertimos a json

$arrayJson = json_encode($results);

//Verificamos el contenido de nuestro json_encode
print_r($arrayJson);

exit();
?>
    
answered by 12.04.2018 в 17:58
1

You may be recovering data in an encoding that is not utf8, try to put:

If you are using mysql

mysql_query ('SET CHARACTER SET utf8') before your query SELECT

If you are using PDO

$sql->exec("set names utf8");

Or if you use mysqli

$mysqli->set_charset("utf8");
  

You can also put it after your connection to the BD

    
answered by 12.04.2018 в 18:06
1

First you must create the Array ordinarily and then pass it to JSON , the problem is that you are not saving the titles in a Aarray and then convert it:

    $array = array();
    $datos["Libros"] = array();

    while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
    $tmp = array();//Array que almacena los datos de la consulta
    $tmp["titulo"] = $row["titulo"];//Guarda los datos en el objecto "titulo"
    array_push($array,$tmp);//Crea el array con los datos del array "$tmp"

    }

    $datos["Libros"] = $array;
    echo json_encode($datos);
    
answered by 12.04.2018 в 19:21
1

Because of the syntax it seems that you are using PDO . It seems that the array is not being filled with the id of the titles, however, they are being correctly consulted with what is possible that the error is in the type of fetch .

One possible solution could be to specify it directly as a parameter of the fetch() function, thus remaining:

$sql->fetch(PDO::FETCH_OBJ)

The complete code would look like this:

<?php
...
$sql = $conn->prepare('SELECT titulo FROM noticias');
$sql->execute();

while($row = $sql->fetch(PDO::FETCH_OBJ)) {
 $data['titulo'] .= " ".$row->titulo." ";    
}

echo json_encode($data);   
exit();
?>
    
answered by 12.04.2018 в 17:52
0

What happens is that JSON expects a array and you send it a string, test in your loop that it is a array instead of a string and that way it will be possible to convert it to a JSON format.

<?php
...
$sql = $conn->prepare('SELECT titulo FROM noticias');
$sql->execute();

while($row = $sql->fetch(PDO::FETCH_OBJ)) {
$data['titulo'][] = $row->titulo;    
}

echo json_encode($data);   
exit();
?>

To provide a better context related to the use of indexed arrays or anonymous objects, a related example follows:

// FETCH_ASSOC -- Arreglo indexado ver ref. bibliografica
$stmt = $dbh->prepare("SELECT titulo FROM noticias");
// Especificamos el fetch mode antes de llamar a fetch()
$stmt->setFetchMode(PDO::FETCH_ASSOC);
// Ejecutamos
$stmt->execute();
// Mostramos los resultados
while ($row = $stmt->fetch()){
    echo "Nombre: {$row["titulo"]} <br>";
}
// FETCH_OBJ -- Objeto anónimo ver Ref. bibliografica
$stmt = $dbh->prepare("SELECT titulo FROM noticias");
// Ejecutamos
$stmt->execute();
// Ahora vamos a indicar el fetch mode cuando llamamos a fetch:
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
    echo "Nombre: " . $row->titulo . "<br>";
}

Bibliography: link

I hope you find it useful.

    
answered by 12.04.2018 в 17:21