user5616242
user5616242

Reputation:

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 ".

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

I appreciate every comment and help!

Upvotes: 0

Views: 8603

Answers (3)

ChristianF
ChristianF

Reputation: 2061

An alternative to nested loops, if you know the number of fields and said number is constant for each execution; A state that's found in most situations; You can use vsprintf () to print out the rows.

Quick example:

$result = {{'John', 'Doe'}, {'Sarah', 'Jane'}};
$output = '<table>';
foreach ($result as $row) {
   $output .= vsprintf ("<tr><td>%s</td><td>%s</td></tr>\n", $row);
}
echo $output."</table>";

Cuts down a bit on the code, and quite a bit on the code complexity. The template for the rows themselves can also be extracted to a variable (or template view), outside of the loop, to make the code even cleaner.

Upvotes: 0

RemanBroder
RemanBroder

Reputation: 117

A nested foreach loop should work.

foreach ($result as $values)
{
  foreach ($values as $value) {
    echo "<table><tr><td>'$value'</td></tr></table>";
  }
}

Upvotes: 0

Ben Hillier
Ben Hillier

Reputation: 2104

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.

Upvotes: 7

Related Questions