使用php从mysql中获取并显示多个行和列

时间:2017-08-21 12:22:04

标签: php mysql

这是我的数据库表:

Database table

我想在单击按钮(列表用户)时在我的页面上显示此表(5列)。

但是我得到以下输出:

Output table

我的代码是:

<?php
$db = "*";  //masked for security
$host = "*"; //masked for security
$user = "*";//masked for security
$pwd = "*; //masked for security
$con = mysqli_connect($host,$user,$pwd,$db);
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

$sql="SELECT login_id,user_name,password,user_role,status_id FROM login";
$select = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($select);
echo "Number of rows : ";
echo $num_rows;
$row = mysqli_fetch_array($select, MYSQLI_ASSOC);
echo "<table>
<tr>
<th>Login ID</th>
<th>User name</th>
<th>Password</th>
<th>User Role</th>
<th>Status ID</th>
</tr>";

foreach ($row as $rows)
{
    echo "<tr>";
    echo "<td>" . $rows['login_id'] . "</td>";
    echo "<td>" . $rows['user_name'] . "</td>";
    echo "<td>" . $rows['password'] . "</td>";
    echo "<td>" . $rows['user_role'] . "</td>";
    echo "<td>" . $rows['status_id'] . "</td>";
    echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

请帮我找到此代码中的错误。

2 个答案:

答案 0 :(得分:1)

d['x']只获得一行 你应该循环结果

mysqli_fetch_array($select, MYSQLI_ASSOC);

现在,如果while($row= mysqli_fetch_array($select, MYSQLI_ASSOC) { your code here ... }循环播放同一行的次数与列数一样多。

答案 1 :(得分:1)

你错了一些条件所以使用这个代码可以工作,只有while ($rows = mysqli_fetch_array($select, MYSQLI_ASSOC))才能用于列出数据所以不需要双循环

<?php
$db = "*";  //masked for security
$host = "*"; //masked for security
$user = "*";//masked for security
$pwd = "*"; //masked for security
$con = mysqli_connect($host, $user, $pwd, $db);
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

$sql = "SELECT login_id,user_name,password,user_role,status_id FROM login";
$select = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($select);
echo "Number of rows : ";
echo $num_rows;

echo "<table>
<tr>
<th>Login ID</th>
<th>User name</th>
<th>Password</th>
<th>User Role</th>
<th>Status ID</th>
</tr>";
if ($num_rows > 0) {

    while ($rows = mysqli_fetch_array($select, MYSQLI_ASSOC)) {
        echo "<tr>";
        echo "<td>" . $rows['login_id'] . "</td>";
        echo "<td>" . $rows['user_name'] . "</td>";
        echo "<td>" . $rows['password'] . "</td>";
        echo "<td>" . $rows['user_role'] . "</td>";
        echo "<td>" . $rows['status_id'] . "</td>";
        echo "</tr>";
    }
}
echo "</table>";
mysqli_close($con);
?>

了解更多信息

https://www.w3schools.com/php/php_mysql_select.asp