This.Sven This.Sven - 2 months ago 9
PHP Question

Php - Array to string conversion

I want to output all records in my database. So far so good, but when I loop through it, php gives me an error " Array to string conversion ".


  • I added an index to the array but then it does just output obviously the first or secound ( etc. ) column.

    $conn = new PDO("mysql:host=localhost;dbname=database","root","");
    $stmt = $conn->prepare('SELECT * FROM de');
    $stmt ->execute();
    $result = $stmt ->fetchAll();

    if (is_array($result) || is_object($result))
    {
    foreach ($result[0] as $value)
    {
    echo "<table><tr><td>'$value'</td></tr></table>";
    }
    }



So, with the index, it does work. But I need all records, not just one.

I appreciate every comment and help!

Answer

I would start with a nested loop. I also wonder if you want a table for every value

$conn = new PDO("mysql:host=localhost;dbname=database","root","");
$stmt = $conn->prepare('SELECT * FROM de');
$stmt ->execute();
$result = $stmt ->fetchAll();

if (is_array($result) || is_object($result))
{
    foreach ($result as $row){  //Go through every row in the result
        echo('<table>');
        foreach ($row as $value){    //Go through every value in the row
            echo "<tr><td>'$value'</td></tr>";
        }
        echo('</table>');
    }
}

This will print every row as a new table, but you can search out the variation you want.

Comments