简体   繁体   中英

PHP/SQL - Query not showing all data

Here's the code:

            <?php 
            if(isset($_POST['results']) && $_POST['results'] != -1) {
            $db = new PDO('mysql:host=localhost;dbname=;charset=utf8', '', '');

            echo "<table border='1'>
            <tr>
            <th>Courses</th>
            </tr>";

            $stmt = $db->prepare("SELECT title FROM course WHERE `subject_id`=?");
            $stmt->execute(array($_POST['results']));

            if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

                     while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

                     echo "<tr>";
                     echo "<td>", $row['title'], "</td>";
                     echo "</tr>";

                     }

            } else {
                    echo "No results found";
                } echo "</table>"; 
            }

            ?>

This is just returning one result into the table, when there are more results to show.

Where am I going wrong?

remove the if, because it's change the pointer of array(fetch)

if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // get the first record, remove this if
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {// get the second record and reset $row

you can change to:

$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$total_rows = $stmt->rowCount();

if($total_rows > 0){

   foreach($row as $item){
      echo '<td>'. $item['title'] .'</td>';
   }
}else{
  echo 'no results';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM