[英]PHP 'IN' query returns only 1 row
Can anyone explain me why the last query returns always 1 row. 谁能解释一下为什么最后一个查询总是返回1行。 it should return more than 1 because there're a lot of records in the database!
它应该返回大于1的值,因为数据库中有很多记录!
Sorry for my bad english 对不起,我的英语不好
$query=mysql_query("SELECT book_id FROM ".DB_PREF."books_cats_list WHERE cat_id='".$cat."'");
if($row=mysql_num_rows($query))
{
//fetching all books from $cat category
for($i=0; $fetch=mysql_fetch_assoc($query); $i++)
{
$records[$i]=$fetch['book_id'];
}
//Joining all records in a string for next query
$records=implode(",",$records);
//returning num rows if there're book_id records in $records array
$query=mysql_query("SELECT * FROM ".DB_PREF."books WHERE book_id IN ('".$records."')");
$rows=mysql_num_rows($query);
echo $rows;
Your query is going to look like this: 您的查询将如下所示:
SELECT * FROM books WHERE book_id IN ('2,3,4,5')
Note how inside the IN
, it's all one string. 请注意,在
IN
,它全都是一个字符串。 This one string will be converted to an int. 这一个字符串将被转换为int。 This happens by stopping at the 1st non-number character.
这是通过在第一个非数字字符处停止来实现的。 So, the query becomes:
因此,查询变为:
SELECT * FROM books WHERE book_id IN (2)
Try to remove the single quotes inside the IN
. 尝试删除
IN
中的单引号。
NOTE: If your values aren't ints, try changing the the implode
to: implode("','",$records)
, and keep the quotes inside the IN
. 注意:如果您的值不是整数,请尝试将
implode
更改为: implode("','",$records)
,并将引号保留在IN
。
At a quick glance I suggest the for loop: 乍一看,我建议使用for循环:
for($i=0; $fetch=mysql_fetch_assoc($query); $i++)
Should be a while loop: 应该是while循环:
while($fetch=mysql_fetch_assoc($query))
I expect it is only doing one record with that for loop code. 我希望它只为循环代码做一条记录。
I suggest however you do a left join select 我建议你做一个左联接选择
SELECT * FROM books_cats_list as cat
left join books as book on cat.book_id = book.book_id
WHERE cat.cat_id='$cat'
This will be far more optimal in terms of database performance I expect. 就我期望的数据库性能而言,这将是最佳选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.