我试图从我的MySQL数据库中返回四条记录,但是只返回了第一条记录。我已经搜过了,但我不知道为什么。有人能给我指明正确的方向吗?
<?php
session_start();
function displayImage($username){
$imageDate = $_POST['imageDate'];
$result = mysql_query("
SELECT
imageName
FROM
images AS i
INNER JOIN
users AS u ON i.userID = u.UserID
WHERE
u.username = '$username'
AND
i.imageDate = '$imageDate'
") or die(mysql_error());
//return a message to the users explaining ......
if (!isset($_POST['Submit'])) {
// this does nowt yet!!!
$output = "Nothing selected yet.";
}
else {
//This is a while loop to store the SQL results into ......
$row = array(mysql_fetch_assoc($result));
foreach ($row as $picName) {
$cam = $_POST['cam'];
$fullPath = $username . "/" . $cam . "/" . $picName['imageName'];
// $output = //this works fine
reset($images);
}
}
var_dump($row);
echo "<br />";
return $output;
}
?>发布于 2014-04-07 09:19:19
正如这里的其他人说的那样,您需要使用一个while循环来完成这个任务,我已经整理了一些代码,并添加了一些其他的内容供您考虑。
这样做的实际原因是,当您使用mysql_fetch_assoc时,它会返回一个结果资源,并从它留给返回的资源中删除它。所以,如果你试着把它存储在一个数组中,你就会得到数组中的第一个,而没有别的东西。当您使用while循环时,它的工作方式基本上是:“如果mysql_fetch_assoc有什么要提供的,那么在循环中执行代码”。
<?php
session_start();
function displayImage($username) {
// Also, as others have said, check out PDO, or MySQLi, as they
// both provide a better interface with MySQL an have better
// security features.
$username = mysql_real_escape_string($username);
$imageDate = mysql_real_escape_string($_POST['imageDate']);
$result = mysql_query("
SELECT
imageName
FROM
images AS i
INNER JOIN
users AS u ON i.userID = u.UserID
WHERE
u.username = '$username'
AND
i.imageDate = '$imageDate'
") or die(mysql_error());
//return a message to the users explaining
if (!isset($_POST['Submit'])) {
// this does nowt yet!!!
$output = "Nothing selected yet.";
} else {
$cam = $_POST['cam'];
$images = array(); // This is part of the "you could do something
// like" further down.
while ($row = mysql_fetch_assoc($result)) {
$fullPath = $username . '/' . $cam . '/' . $row['imageName'];
// $output = //this works fine
var_dump($row);
echo "<br />";
// Or you could do something like:
$images[] = $username . '/' . $cam . '/' . $row['imageName'];
// Then outside of this while loop you'd have all of your image
// paths stored in this $images array.
//
// It depends on how you want to handle outputting them.
}
}
return $output;
}代码中的注释贯穿我的主要观点。
我还将$cam =$_POST‘$cam’从循环内部移到了它的外部,因为它不需要进入循环,因为它的值总是相同的,不管您要遍历哪个循环项。
发布于 2014-04-07 09:03:06
您应该使用循环来获取结果:
while ($row = mysql_fetch_assoc($result)) {
$cam = $_POST['cam'];
$fullPath = $username . "/" . $cam . "/" . $row['imageName'];
}发布于 2014-04-07 09:15:26
使用mysql_fetch_assoc或mysql_fetch_array的方法如下:
while ($row = mysql_fetch_assoc($result)) {
// This is an example...
echo $row["id"];
echo $row["name"];
}https://stackoverflow.com/questions/22907892
复制相似问题