Error Notice: Array to string conversion in PHP PDO

1

Could someone help me and say why he sends me that message?

Attach the code:

<?php

try{
    $conexion = new PDO('mysql:host=localhost;dbname=organizer', 'root', ''); } catch(PDOexception $e){
    echo 'Error ' . $e->getMessage(); }

?>

<!DOCTYPE html> <html lang="en"> <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/estilos-inicio.css">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TASKS | Reportes no tan importantes</title>

</head>
<body>
    <?php require('views/header.php'); ?>

        <div class="contenedor">    
            <div class="post">
                <p class="titulo">REPORTES NO TAN IMPORTANTES</p>
                <br>
                <hr>
                <article>
                    <?php 
                       foreach($reportes = $conexion->query('SELECT descripcion FROM tareas WHERE categoria = "No tan importante"') as $reporte){ // ESTA LINEA ES LA DEL ERROR!!!!!
                            echo '<li>' . $reporte . '</li>';
                        }
                    ?>
                </article>
            </div>  
        </div>

    <?php require('views/footer.php'); ?>
</body>
</html>
    
asked by Emanuel Mejia 06.04.2018 в 02:00
source

2 answers

1

The error is quite simple, by using $ pdo-> query () directly, you will get the data with the style fetch_style PDO::FETCH_BOTH that is to say it is possible to access by means of numerical index and index of the name of the column in select . Therefore, its variable $ report is of type array and it is not possible to concatenate it directly.

echo '<li>' . $reporte[0] . '</li>';  //Esta opción
echo '<li>' . $reporte['descripcion] . '</li>'; //Otra opción

The solution can be the previous or specify the style of obtaining the data, for your case with FETCH_COLUMN would be enough, that is

foreach($reportes = $conn->query('SELECT descripcion FROM sexo WHERE descripcion = "m" ')
                         ->fetchAll(PDO::FETCH_COLUMN) as $reporte)

But it looks very confusing and little readable the code as it is, you should get the data before entering the foreach , (example)

$conexion = new PDO('mysql:host=localhost;dbname=organizer', 'root', ''); 
$conexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$data = $conn->query('SELECT descripcion FROM tareas WHERE categoria = "No tan importante" ')
            ->fetchAll(PDO::FETCH_COLUMN);
foreach($data as $reporte){ 
    echo '<li>' . $reporte . '</li>';
}
    
answered by 06.04.2018 / 03:12
source
0

You should probably call the array element in the foreach by its respective index:

echo '<li>' . $reporte['descripcion'] . '</li>';
    
answered by 06.04.2018 в 03:13