我不确定如何解释查询的作用,但问题并不完全在于如何设置,因为它确实有效,在另一个例子中,当我将它用作数组时,但它不是当我使用mysql_fetch_assoc()时工作,所以这是我的原始查询(不是我遇到问题的那个):
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC
这样做是选择帖子上的最后3条评论,然后以另一种方式对它们进行排序(因此它们以正确的顺序显示,从旧到新)现在这是直接回显注释数组的查询。 但现在我想要做的就是从3条评论中获得第一个id。
这是我试图做的事情(顺便说一下,这个查询工作,当我替换我以前的查询以回应数组中的结果,但我需要得到使用的ID,我不要我想要一个数组):
$previousIDq = mysql_fetch_assoc(mysql_query("
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1"));
$previousID = $previousIDq['id']; //this doesn't return the id as I want it to.
答案 0 :(得分:1)
您的问题可能是没有匹配的行。
此外,我认为您还可以改进您的查询:
SELECT * FROM comments WHERE postID='$id' AND state='0' ORDER BY id DESC LIMIT 2,1
但正如其他人所说,使用PDO或MySQLi,并使用预备语句。并且不要选择*永远。
答案 1 :(得分:0)
尝试使用var_dump($ previousID)来查看你得到的内容
它可能会给你一个对象,你需要从该对象获取你的id
答案 2 :(得分:0)
请停止使用mysql_
函数编写新代码,它是being deprecated。使用mysqli_
或PDO
函数(下面为mysqli
)。
SELECT *
)while
循环mysqli_
解决方案$link = mysqli_connect("localhost", "user_name", "password", "stock");
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$stmt = mysqli_prepare($link, "SELECT t.id FROM
(SELECT id FROM comments
WHERE postID = ? AND state = 0
ORDER BY id DESC
LIMIT 3) t
ORDER BY id ASC");
mysqli_bind_param($stmt, 's', $id) or die(mysqli_error($dbh));
$result = mysqli_stmt_execute($stmt) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($result)) {
echo $row[id];
}
mysqli_close($link);
mysql_
解决方案$stmt = "SELECT t.id FROM
(SELECT id FROM comments
WHERE postID = $id AND state = 0
ORDER BY id DESC
LIMIT 3) t
ORDER BY id ASC";
$result = mysql_query($stmt) or die(mysql_error());
$row = mysql_fetch_assoc($result);
while($row = mysql_fetch_assoc($result)) {
echo $row[id];
}
答案 3 :(得分:0)
您的脚本过于简洁,无法进行错误处理,更不用说调试了
$mysql = mysql_connect(...
$query = "
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1
";
$result = mysql_query($query, $mysql);
if ( !$result ) { // query failed
die('<pre>'.htmlspecialchars(mysql_error($mysql)).'</pre><pre>'.htmlspecialchars($query).'</pre>');
}
$previousIDq = mysql_fetch_assoc($result);
if ( !$previousIDq ) {
die('empty result set');
}
else {
$previousID = $previousIDq['id'];
}
答案 4 :(得分:0)
您需要将代码分开才能调试
$query = "SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1";
$result = mysql_query($query);
echo mysql_error(); //what eror comes out here
while($previousIDq = mysql_fetch_assoc($result))
{
print ($previousIDq['id']);
}
注意: mysql_ *已折旧,升级到mysqli或PDO