过滤职位取决于类别的ID与PHP


Filter Posts depending ID of categorie with PHP

我有一个小任务,我有一个mysql表"博客"。它包含一个列"ID_CAT"。ID_CAT的每个字段包含单个文章的不同类别值,如"22,44,33,55"。我想过滤博客的帖子取决于类别选择。我将ID_CAT选择传递到包含的页面中的URL和GET方法,如

<a class="rotated_link" href="?cat='.$categorie->getIDCategorie().'">'.$categorie->getNomCategorie().'</a>

然后像这样包含

$id_categorie = $_GET["cat"];
if (isset($id_categorie)) {
  foreach(Article::getAllArticlebycategorie($id_categorie) as $all){
                $article= new Article($all->ID_BLOG);
                $img=Image::getImageByArticle($article->getIDarticle());
                $tblCat=explode(',',$article->getIDCategorie());
                    echo '<li class="li_blog_post">';
                            echo'<img class="img_post_mini" src="img/file/'.$img.'" style="width:100%; height:150px; border:1PX solid #9D9D9D;" />';
                            echo'<span class="post_title0">'.$article->getTitlearticle().'</span>';
                            echo'<span class="tag_post"><img src="img/tag.png" style="width:16px; height:16px;"/>';
                    foreach($tblCat as $catt){
                        $categoriea = new Categorie($catt);
                    echo '<a class="tag_lable" href="">'.$categoriea->getNomCategorie().'</a> </span>';
                    }
                    echo'<p class="post_prev">'.substr($article->getArticle(), 0, 410).'&nbsp;...</p>';
                    echo'<span class="date">le&nbsp;'.$article->getDatearticle().'</span> <span class="view_more"><a class="test" href="?article='.$article->getIDarticle().'">voire les détails</a></span>';
                   echo '</li>';
                }  
}

问题是当我选择例如ID_CAT=4时,函数getallarticlebycategory仅当数字4是列ID_CAT(4,33,50)->选择(3,4,10)->未选择的第一个值时返回帖子。功能:

public static function getAllArticlebycategorie($id_categorie){
    global $db;
    $req = $db->prepare('SELECT * FROM blog WHERE ID_CAT='.$id_categorie);
    $req->execute();
    return $req->fetchAll(PDO::FETCH_OBJ);
}

使用FIND_IN_SET(),因为您使用的是PDO,所以使用参数化查询。

因此改变

$req = $db->prepare('SELECT * FROM blog WHERE ID_CAT='.$id_categorie);
$req->execute();

$req = $db->prepare("SELECT * FROM blog WHERE FIND_IN_SET('$id_categorie', ID_CAT)");
$req->execute(array(':id_categorie' => $id_categorie));

SQLFiddle for you play with FIND_IN_SET()