Php 数组内sql查询
我在foreach循环中有以下内容(显示我的各种视频),我试图为前三名投票的视频显示一些备选文本。我到底做错了什么(很明显)Php 数组内sql查询,php,sql,arrays,Php,Sql,Arrays,我在foreach循环中有以下内容(显示我的各种视频),我试图为前三名投票的视频显示一些备选文本。我到底做错了什么(很明显) mysql_fetch_数组只返回一行,您需要循环搜索结果以构建包含前三个ID的数组 $sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3"; $result = mysql_query($sql); while($row = @mysql_fetch
mysql_fetch_数组只返回一行,您需要循环搜索结果以构建包含前三个ID的数组
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
$result = mysql_query($sql);
while($row = @mysql_fetch_array($result)) {
$topthree[] = $row["video_id"];
}
然后可以使用in_数组,但语法正确:
if(in_array($video->getProperty('video_id'), $topthree)) {
do this...
} else {
do this..
}
首先用一些防止错误的技术来替换你的代码,就像这样
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
if(false != ($result = mysql_query($sql))
{
$row = mysql_fetch_assoc($result); //Dont need the @ restraint as the result is not false above.
//Also to get associate keys you need to use mysql_fetch_assoc
if($video->getProperty('video_id') == $row['video_id'])) //Remove the in array as your directly comparing the to entities with ==
{
//Match
}else
{
//Video does not match
}
}
您的主要问题是mysql_fetch_array(),请研究与mysql_fetch_array()和mysql_fetch_assoc()的区别
--
编辑:我会走的路
//Change the query and the loop way.
$sql = "SELECT video_id FROM videos WHERE displayable='y' AND video_id != '".(int)$video->getProperty('video_id')."' ORDER BY votes desc LIMIT 0,3";
if(false != ($result = mysql_query($sql))
//Use the @ restraint if you have E_NOTICE on within E_Reporting
{
while($row = mysql_fetch_assoc($result))
{
//Print the $row here how you wish for it to be displayed
}
}else
{
//We have an error?
echo '<strong>Unable to list top rated videos, please check back later.</strong>'
}
}
//更改查询和循环方式。
$sql=“从可显示的视频中选择视频id='y'和视频id!='”(int)$video->getProperty('video\u id')。“'ORDER BY vows desc LIMIT 0,3';
if(false!=($result=mysql\u查询($sql))
//如果您在E_报告中有E_通知,请使用@restrict
{
while($row=mysql\u fetch\u assoc($result))
{
//在此处按您希望的方式打印$行
}
}否则
{
//我们有错误吗?
echo“无法列出顶级视频,请稍后再查看。”
}
}
是的,谢谢,我知道其中的区别,就是了解其重要性。另一种方法是通过修改查询来选择当前视频的前3个栏,就像这样$sql=“从可显示的视频中选择视频id='y'和视频id!='”(int)$video->getProperty('video_id')。“'ORDER by vows desc LIMIT 0,3”;
那么你就不需要if()语句就可以将当前视频从前三名列表中删除。为此干杯,这正是我的目标,而且效果很好。他没有“前三名”但是,他通过查询选择了前3名,并确保他没有在“从数据库中选择的项目”中播放当前视频。为了澄清,它们都很好地工作,我觉得我必须接受他的回答,因为这是第一个答案,并采用了较短的方法。
//Change the query and the loop way.
$sql = "SELECT video_id FROM videos WHERE displayable='y' AND video_id != '".(int)$video->getProperty('video_id')."' ORDER BY votes desc LIMIT 0,3";
if(false != ($result = mysql_query($sql))
//Use the @ restraint if you have E_NOTICE on within E_Reporting
{
while($row = mysql_fetch_assoc($result))
{
//Print the $row here how you wish for it to be displayed
}
}else
{
//We have an error?
echo '<strong>Unable to list top rated videos, please check back later.</strong>'
}
}