我想回显数组中的多行,但它只输出一行: PHP
$query = "SELECT * FROM user WHERE Category = 'Men'";
$result = mysql_query($query);
while ($row1 = mysql_fetch_array($result)) {
$fname1 = $row1['FName'];
$sname1 = $row1['SName'];
}
$result2 = mysql_query($query);
while ($row2 = mysql_fetch_array($result2)) {
$fname2 = $row2['FName'];
$sname2 = $row2['SName'];
}
HTML
<h2>First Name: <?php echo "$fname1"; ?></h2>
<h2>Second Name: <?php echo "$sname1"; ?></h2>
<h2>First Name: <?php echo "$fname2"; ?></h2>
<h2>Second Name: <?php echo "$sname2"; ?></h2>
但是当两者都不同时,它给出了相同的输出。 输出是:
名字:约翰 第二名:史密斯
名字:约翰 第二名:史密斯
当我希望输出为:
名字:约翰 第二名:史密斯
名字:鲍勃 第二名:马利
有人可以帮我解决这个问题吗?\
数据库中的数据是:
User_ID| FName |SName| Category
1 John Smith Men
2 Bob Marley Men
答案 0 :(得分:2)
while循环会一遍又一遍地覆盖你的变量而只输出最后的结果,你必须将echo放在while中或者将它保存到数组然后循环遍历数组
也必须“停止使用mysql_ functions”并更改为PDO:)
您的代码的解决方案将是
$query = "SELECT * FROM user WHERE Category = 'Men'";
$result = mysql_query($query);
while ($row1 = mysql_fetch_array($result)) {
?> <h2>First Name: <?php echo $row1['FName']; ?></h2>
<h2>Second Name: <?php echo $row1['SName']; ?></h2><?php
}
答案 1 :(得分:1)
使用数组,也只是跟踪你的代码。
PHP:
$query = "SELECT * FROM user WHERE Category = 'Men'";
$result = mysql_query($query);
$fname=array();
$sname=array();
for($i=0;$i<2 && ($row = mysql_fetch_array($result));$i++) {
$fname[$i] = $row['FName'];
$sname[$i] = $row['SName'];
}
HTML:
<h2>First Name: <?php echo "$fname[0]"; ?></h2>
<h2>Second Name: <?php echo "$sname[0]"; ?></h2>
<h2>First Name: <?php echo "$fname[1]"; ?></h2>
<h2>Second Name: <?php echo "$sname[1]"; ?></h2>
答案 2 :(得分:0)
$query = "SELECT * FROM user WHERE Category = 'Men'";
$result = mysql_query($query);
while ($row1 = mysql_fetch_array($result)) {
$fname1 = $row1['FName'];
$sname1 = $row1['SName'];
echo " <h2>First Name: $fname1</h2>";
echo "<h2>Second Name: $sname1</h2>";
}
答案 3 :(得分:0)
您正在覆盖您的值,因为您的while
循环每次都在迭代每一行。试试这个:
$query = "SELECT * FROM user WHERE Category = 'Men'";
// mysql_ = bad. mysqli_ = good!
$result = mysql_query($query);
$row1 = mysql_fetch_array($result);
$fname1 = $row1['FName'];
$sname1 = $row1['SName'];
// using the same $result.
$row2 = mysql_fetch_array($result);
$fname2 = $row2['FName'];
$sname2 = $row2['SName'];
当然,正如其他地方所述,如果您的表中有两个以上的项目并且想要输出中的每个项目,那么此解决方案将无效。如果是这种情况,你会想要这样的东西:
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
?> <h2>First Name: <?=$row['FName'] ?></h2>
<h2>Second Name: <?=$row['SName'] ?></h2><br /><?php
}
或者,根据您的需要:
$result = mysql_query($query);
$men = array();
while($row = mysql_fetch_array($result))
{
$men[] = $row;
}
// then later in the script
foreach($men as $man)
{
// extract takes all of the array keys and turns them into local variables.
// just make sure you read the warnings in the docs:
// http://php.net/manual/en/function.extract.php
extract($man);
?>
<h2>First Name: <?=$FName ?></h2>
<h2>Second Name: <?=$SName ?></h2><br /><?php
}