我有一个包含这样数据的表:
articles. id | author | title | content | type
1 | author1, author2 | thetitle1 | text1 | typeA
2 | author1 | thetitle2 | text2 | typeB
3 | author2 | thetitle3 | text3 | typeA
Posted array 是一个过滤器:
$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
的文章(本例为第一条和第二条记录)?
最佳答案
我认为您需要更改数据库结构。通过字符串搜索很慢(差不多),这现在可能可行,但当数据集增加时,这将成为一种拖累。
我认为像这样的东西会更好:
author
--------
id name
1 author1
2 author2
books:
--------
id title
1 Some Book
2 Some Other Book
author_book:
--------
id author_id book_id
1 1 1
2 1 2
3 2 2
在我的例子中,作者 1 写了书 1 和 2,作者 2 写了书 2 另一个是:第 1 本书由作者 1 撰写,第 2 本书由作者 1 和 2 撰写
从长远来看,它更加灵活。开始时正确的数据库结构非常重要
关于php - 通过发布的数组过滤数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18012723/