SQL表只回显1行而不是所有行

时间:2016-02-22 17:27:16

标签: php mysql

我有一个表来从我的数据库中获取条目,但是该表只输出它找到的第一个结果而不是数据库中的其余条目。

$query = "SELECT * FROM aliases where client_id='$userid'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$timesused=$row['num_used'];
$alias=$row['alias'];
$firstused=$row['time_add'];
$firstused = date('d M Y H:i:s', $firstused);
$lastused=$row['time_edit'];
$lastused = date('d M Y H:i:s', $lastused);
echo "<table border=1>";
echo "<tr>";
echo "<th>Alias</th>";
echo "<th>Times Used</th>";
echo "<th>First Used</th>";
echo "<th>Last Used</th>";
echo "</tr>";
echo "<tr align=center>";
echo "<td>$alias</td>";
echo "<td>$timesused</td>";
echo "<td>$firstused</td>";
echo "<td>$lastused</td>";
echo "</tr>";
echo "</table>";

3 个答案:

答案 0 :(得分:0)

mysql_fetch_assoc函数从结果中返回一行(您甚至调用您指定其返回值$row的变量)。您需要在所有结果的循环中迭代以获取所有行,例如:

while ($row = mysql_fetch_assoc($result)) {
  $timesused=$row['num_used'];
  $alias=$row['alias'];
  $firstused=$row['time_add'];
  $firstused = date('d M Y H:i:s', $firstused);
  $lastused=$row['time_edit'];
  $lastused = date('d M Y H:i:s', $lastused);
    echo "<table border=1>";
    echo "<tr>";
    echo "<th>Alias</th>";
    echo "<th>Times Used</th>";
    echo "<th>First Used</th>";
    echo "<th>Last Used</th>";
    echo "</tr>";
    echo "<tr align=center>";
    echo "<td>$alias</td>";
    echo "<td>$timesused</td>";
    echo "<td>$firstused</td>";
    echo "<td>$lastused</td>";
    echo "</tr>";
    echo "</table>";
}

答案 1 :(得分:0)

试试这个:

$query = "SELECT * FROM aliases where client_id='$userid'";
$result = mysqli_query($query);

$timesused=$row['num_used'];
$alias=$row['alias'];
$firstused=$row['time_add'];
$firstused = date('d M Y H:i:s', $firstused);
$lastused=$row['time_edit'];
$lastused = date('d M Y H:i:s', $lastused);

echo "<table border=1>";
echo "<tr>";
echo "<th>Alias</th>";
echo "<th>Times Used</th>";
echo "<th>First Used</th>";
echo "<th>Last Used</th>";
echo "</tr>";

while($row = mysqli_fetch_array($result)){
echo "<tr align=center>";
echo "<td>$alias</td>";
echo "<td>$timesused</td>";
echo "<td>$firstused</td>";
echo "<td>$lastused</td>";
echo "</tr>";
}
    echo "</table>";

请注意,不推荐使用mysql_ *函数。相反,请使用MySQLi或PDO_MySQL扩展。

答案 2 :(得分:0)

使用while循环显示表格中的所有记录(mysql_fetch_assoc($ result) 它会显示所有记录。