-2

I am trying to pull data from the database based on my search input. It works, however I receive only one row as a result, even if the query is sending an array. I think I have to put fetch in a while loop somehow.

<?php
$con = new PDO("mysql:host=localhost;dbname=va_final_project", 'root', '');
if (isset($_POST["submit"])) {
    $str = $_POST["search"];
    $sth = $con->prepare("SELECT gr.genre_name AS gr_name, band_name AS name_band
    FROM `va_band_name` bn INNER JOIN va_genre gr ON bn.genre_id = gr.id
    WHERE band_name = '$str' OR genre_name = '$str'");

    $sth->setFetchMode(PDO::FETCH_OBJ);
    $sth->execute();
    if ($row = $sth->fetch()) {

        while($row = $sth->fetch()) {
?>
        <div class="separate">
            <table id="bands_table_display" class="table table-dark">
                <tr>
                    <th>Genre</th>
                    <th>Band</th>
                </tr>
                <tr>
                    <td><?php echo $row->gr_name; ?></td>
                    <td><?php echo $row->name_band; ?></td>
                </tr>

            </table>
        </div>

<?php
        }
    } else {
        echo "<h3 class='separate no-response'>Name Does not exist</h3>";
    }
}

?>
ADyson
  • 51,527
  • 13
  • 48
  • 61
Vladimir
  • 105
  • 5
  • https://www.php.net/manual/en/pdostatement.fetch.php#refsect1-pdostatement.fetch-examples Example #2 has a good example of using a while loop to fetch – aynber May 26 '22 at 16:32
  • You may use `do {...} while()`, or `while() {...}` with `fetch()`, they are good. Or you may use [`fetchAll()`](https://www.php.net/manual/en/pdostatement.fetchall.php). – vee May 26 '22 at 16:39
  • I wouldn't suggest a `do{}while()` loop, as that wouldn't fetch the result until the end of the first loop. – aynber May 26 '22 at 16:48
  • I think I am doing something wrong.. Could you help me here? I'm novice to this. :( – Vladimir May 26 '22 at 16:53
  • 3
    Remove the `if ($row = $sth->fetch())`, you're unnecessary retrieving the first row – aynber May 26 '22 at 17:23
  • For checking there is **no** result, you may use `if (!$sth->fetch()) {..}` or `if (!$sth->rowCount()) {...}`. – vee May 26 '22 at 17:25

0 Answers0