我正在查询数据库中的结果,其中应查询多个结果。但是,当我尝试显示查询结果时,只显示了一个结果,所以我尝试使用foreach函数,但它仍然无效。我被打败了,不知道我做错了什么。任何人都知道出了什么问题?
这是MySQL查询代码:
<?php
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$filename = $_GET['filename'];
$new_captions = mysql_query("SELECT * from captions where image = 'http://math.stanford.edu/inc/img/PalmDrive.png' ORDER BY idnum DESC LIMIT 5");
while($rows = mysql_fetch_array($new_captions)){
$caption = $rows;
}
?>
这是foreach:
<?php foreach($caption as $rows) {?>
<div id="set_caption" style="width:<?php echo $caption['width'];?>px; height:<?php echo $caption['height'];?>px; left:<?php echo $caption['posleft'];?>px; top:<?php echo $caption['postop'];?>px;"><?php echo $caption['text'];?></div>
<?php } ?>
答案 0 :(得分:3)
我认为$ caption是一个数组,所以你的代码应该是这样的
while($rows = mysql_fetch_array($new_captions)){
$caption[] = $rows;
}
编辑:
你的foreach循环也是错误的。
你的变量是$ rows而不是$ caption。
<div id="set_caption" style="width:<?php echo $rows['width'];?>px; height:<?php echo $rows['height'];?>px; left:<?php echo $rows['posleft'];?>px; top:<?php echo $rows['postop'];?>px;"><?php echo $rows['text'];?></div>
<?php } ?>
答案 1 :(得分:1)
您有以下错误。
在foreach中使用$ row变量。
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$filename = $_GET['filename'];
$new_captions = mysql_query("SELECT * from captions where image = 'http://math.stanford.edu/inc/img/PalmDrive.png' ORDER BY idnum DESC LIMIT 5");
$caption = array();
while($rows = mysql_fetch_array($new_captions)){
$caption[] = $rows;
}
foreach($caption as $row) {
<div id="set_caption"
style="width:<?php echo $row['width'];?>px;
height:<?php echo $row['height'];?>px;
left:<?php echo $row['posleft'];?>px;
top:<?php echo $row['postop'];?>px;">
<?php echo $row['text'];?>
</div>
}