次のようなデータを含むテーブルがあります。
articles. id | author | title | content | type
1 | author1, author2 | thetitle1 | text1 | typeA
2 | author1 | thetitle2 | text2 | typeB
3 | author2 | thetitle3 | text3 | typeA
投稿された配列は、このためのフィルターです。
$conditions = array();
$where = '';
if(isset($_POST['authors'])){ //empty, is_array and etc.
$authors = $_POST['authors']; // [ author1, author2 ]
$conditions[] = "author IN ('".implode("','",$authors)."')";
}
if(isset($_POST['types'])){
$types = $_POST['types']; // [ typeA, typeB ]
$conditions[] = "type IN ('".implode("','",$types)."')";
}
if(!empty($conditions)){
$where = ' WHERE '.implode(' AND ', $conditions);
}
$sql = "SELECT * FROM articles".$where;
すべて問題ないようですが、フィールドにauthor
はコンマで区切られた数人の著者が含まれている可能性があるため、フィルターauthor IN ('author1')
は機能しません。関連するすべての記事を選択する方法author1
(この場合は最初と 2 番目のレコード)?