【问题标题】:in array sql query在数组 sql 查询中
【发布时间】:2010-07-01 10:35:41
【问题描述】:

我在 foreach 循环中有以下内容(显示我的各种视频),我正在尝试为投票的前三个视频显示一些替代文本。我到底做错了什么(很清楚)......

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

【问题讨论】:

    标签: php sql arrays


    【解决方案1】:

    首先用一些像这样的错误预防技术替换你的代码!

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

    【讨论】:

    • 是的,谢谢,我知道这些差异,是看到了重要性。
    • 另一种方法是修改查询以选择当前视频的前 3 栏,就像$sql = "SELECT video_id FROM videos WHERE displayable='y' AND video_id != '".(int) $video-&gt;getProperty('video_id')."' ORDER BY votes desc LIMIT 0,3"; 这样您就不需要 if() 语句从前 3 名。
    【解决方案2】:

    mysql_fetch_array 只返回一行,你需要遍历你的结果来构建一个包含前三个 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_array 但语法正确:

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

    【讨论】:

    • 为此欢呼,这就是我的目标并且完美地工作。
    • 他没有“$topthree”,但他通过查询选择了前 3 个,并确保他在从 db 项目中选择的当前播放视频中没有。
    • 澄清一下,它们都工作得很好,我觉得我必须首先接受他的回答并采用更短的方法。
    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多