我们有一个基本的PHP脚本从MySQL数据库中提取每个作业的标题和描述,只需显示此信息。它看起来是这样的:
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
$results = mysql_fetch_assoc($query);
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$results['title']}</h2>";
echo "<p>{$results['desc']}</p>";
echo '</div>';
} ?>现在,这只从数据库中提取一行,但它应该提取两行。因此,我尝试使用以下命令来替换while语句:
<?php foreach($results as $result) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>这个语句也不起作用。这只会(奇怪地)显示表中第一行中每列的第一个字符。
有没有人知道为什么它不能正常工作?
发布于 2012-10-09 18:07:45
您使用的结果变量不是results,而是result
替换
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
**$results = mysql_fetch_assoc($query);** // remove this line
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$results['title']}</h2>";
echo "<p>{$results['desc']}</p>";
echo '</div>';
} ?>至
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>发布于 2012-10-09 18:07:50
在while中,使用与启动时相同的变量$result:
while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
}并删除第一个$results = mysql_fetch_assoc($query);
发布于 2012-10-09 18:08:47
在循环开始之前,您已经获取了第一行,这就是为什么它只打印第二行的原因。只需注释掉这一行:
#$results = mysql_fetch_assoc($query); # here is your first row,
# simply comment this line
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>您还在$result上循环,但在while循环体中使用了$results。
https://stackoverflow.com/questions/12797617
复制相似问题