简体   繁体   中英

MySQL PHP While loop

I'm in need of some help. I'm working in dreamweaver and I'm trying to insert values from my MySQL database into a table on my HTML page.

Dreamweaver generated these variables for me from the server behaviours

mysql_select_db($database_connection, $connection);
$query_mwAcc = "SELECT * FROM accounts";
$mwAcc = mysql_query($query_mwAcc, $connection) or die(mysql_error());
$row_mwAcc = mysql_fetch_assoc($mwAcc);
$totalRows_mwAcc = mysql_num_rows($mwAcc);

Now what I need help with is what to put into the while loop for my PHP script, this is what I have so far

<table class="table table-bordered">
    <?php while (): ?>
        <tr>
            <td><?php echo $row['id'] ?></td>
        </tr>
    <?php endwhile; ?>
</table>

With an update to use PDO you can change the while loop into a foreach on the query result. PDO should be used over mysql_ interface methods, due to deprecation: Why shouldn't I use mysql_* functions in PHP?

<?php
  $dbh = new PDO('mysql:host=...;dbname=...', $user, $pass);
  $results = $dbh->query('SELECT * FROM accounts');
?>
<table class="table table-bordered">
    <?php foreach ($results as $row): ?>
        <tr>
            <td><?php echo $row['id'] ?></td>
        </tr>
    <?php endforeach; ?>
</table>

You need to write your fetch command within the while loop itself.

   $query_mwAcc = "SELECT * FROM accounts";

   $mwAcc = mysql_query($query_mwAcc, $connection) or die(mysql_error());

   while($row_mwAcc = mysql_fetch_assoc($mwAcc)) { 
?>      

<tr>
   <td><?php echo $row_mwAcc['id'] ?></td>
</tr>

<?php } ?>
</table>

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