我可以在选择中的php查询中传递任何值/参数,以便不考虑该特定字段

时间:2015-01-29 12:49:11

标签: php mysql

我是PHP和SQL的初学者。在这里,我正在尝试对我的家庭电影数据库进行过滤 - 这基本上是一个网页,它在我的计算机上显示电影。有四个过滤器(演员,导演,年份和类别),如果我在数据库表中传递每个字段的所有正确值(我不确定它是否被称为列或字段),它列出了所有的海报相应的电影。

但是,如果我想选择演员作为'所有演员'(在过滤时不考虑场演员),我该怎么做?是否有任何特定的论点要通过(我试过'*'但不起作用并且保持空白'',返回所有电影,哪个字段'演员'是空的。

这是我写的函数:

function retrive_movies($actor, $director, $year, $category) {
    echo "<ul>";
    $result = mysql_query("SELECT * FROM `movie` WHERE `actor` = $actor AND `director` = $director AND `year` = $year `category` = $category");
    while($row = mysql_fetch_array($result)) {
        if (empty($row['poster_location']) === false){
            echo "<li><img src=" . $row['poster_location'] . "><p>" . $row['movie_name'] . "</p>User rating: " . $row['user_rating'] . "</p></li>";
        }}

    echo "</ul>";
}

2 个答案:

答案 0 :(得分:1)

这是一种方法

SELECT * FROM `movie` WHERE `actor` LIKE '%$actor%' AND `director` LIKE '%$director%' AND `year` LIKE '%$year%' `category` LIKE '%$category%'

在此查询中,如果您的过滤器为空,则会匹配所有记录,因为&#39; %%&#39;另一种方法是,如果过滤器为空,则使其与自身匹配。

如果'%filter%'无法满足您的需求,则此查询会更合适。

SELECT * FROM `movie` WHERE `actor` = IF($actor = '', `actor`, $actor) AND `director` = IF($director = '', `director`, $director) AND `year` = IF($year = '', `year`, $year) `category` = IF($category = '', `category`, $category)

如果过滤器参数变为空,则查询将与column/field自身匹配,从而始终匹配。

答案 1 :(得分:0)

您可以像下面一样使用它,但未经过测试,

function retrive_movies($actor='', $director='', $year='', $category='') {
echo "<ul>"; 

if($actor!= '' && $director!='' && $year!='' && $category!='') {
$result = mysql_query("SELECT * FROM `movie` WHERE `actor` = $actor AND `director` = $director AND `year` = $year `category` = $category");
} else {
$result = mysql_query("SELECT * FROM `movie` WHERE 1 ");
}

while($row = mysql_fetch_array($result)) {
    if (empty($row['poster_location']) === false){
        echo "<li><img src=" . $row['poster_location'] . "><p>" . $row['movie_name'] . "</p>User rating: " . $row['user_rating'] . "</p></li>";
    }}

echo "</ul>";
}