Search code examples
phphtmlimagehyperlinkdynamic-html

Dynamic HTML image links pulling wrong information from database in PHP


Running XAMPP for Windows 7.2.6. Below is my MariaDB art table from the database.

art table

Code:

<?php

            $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
            $sql = "SELECT * FROM art LIMIT 50";
            $st = $conn->prepare( $sql );
            $st->execute();
            $row = $st->fetch();
            $conn = null;
            if (isset($row)) {

                echo "row has value";

                 foreach ($row as $value) {

                  echo "<a href=\"/admin.php?action=editProducts&product=" . $value[0] . "\"><img src=\"" .  $value[2] .
                        "\" width=\"75\" height=\"75\" title=\"" . $value[6] . "\"></a>";
                  echo "<br>";

                    }
            }

            ?>

HTML Image Links when I inspect the source

<a href="/admin.php?action=editProducts&product=a"><img src=" " width="75" height="75" title="c" ></a>

row has value is printing to the browser and I'm seeing in the debugger that the $row array has the proper values. I can't figure out why it's only pulling 1 random character from the art table instead of the proper values, and my error code for each row is:

Notice: Uninitialized string offset: 1


Solution

  • As you are using

    $row = $st->fetch();
    

    this is just a single row of data from the table, so then using

    foreach ($row as $value) {
    

    just loops across the fields in that 1 row. You need to change it so that the first part retrieves all of the rows in one go using fetchAll()...

    $row = $st->fetchAll();
    

    You probably then should change the value to $rows just for semantic purposes (just to say it is a set of rows and not just one row).