开发者

in array sql query

I have the following inside a foreach loop (displaying my various videos), I'm trying to display some alternate text for the top three voted videos. What on earth am I doing开发者_运维知识库 wrong (a lot clearly)...

$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
$result = mysql_query($sql);
$row = @mysql_fetch_array($result);

if(in_array($video->getProperty('video_id')) == $row['video_id']) {
do this...
} else {
do this..
}


Firstly replace your code with some error preventing techniques like so!

$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
   }
}

Your main problem was the mysql_fetch_array(), Please research the differences with mysql_fetch_array() and mysql_fetch_assoc();

--

Edit: The way i would go

  //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>'
   }
}


mysql_fetch_array only returns a single row, you need to loop through your results to build an array containing the top three ids.

$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"];
}

Then you can use in_array but with the correct syntax:

if(in_array($video->getProperty('video_id'), $topthree)) {
do this...
} else {
do this..
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜