寻找一种更简洁的方法来运行一个必须检查多个" AND"的查询。条件

时间:2015-11-04 17:14:25

标签: mysql

我正在对数据库运行查询,并且必须检查多个条件是否为真。代码我已经提取了我想要的数据,但是如果我必须检查更多的列,它可能会很快失控。我不想要一个查询,我必须写出十几个" AND"条件。我正在学习一些MySQL,任何帮助都会受到赞赏。

 <?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "oldga740_SeniorProject";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
} 

//Set up and run my Query

$sql = "SELECT Project, Client, DateReceived, LastName, FinalReviewDate FROM Projects
          WHERE FinalReviewDate IS NOT NULL
          AND DateDelivered IS NULL
          AND DateAccepted IS NULL
          ORDER BY DateAccepted DESC";
$result = $conn->query($sql);

//Display results

if ($result->num_rows > 0) {
 echo "<table><tr><th>Client</th><th>Project</th><th>Point of     Contact</th><th>Date Project Received</th><th>Final Review Date</th></tr>";
 // output data of each row
 while($row = $result->fetch_assoc()) {
     echo "<tr><td>" . $row["Client"]. "</td><td>" . $row    ["Project"]. "</td><td> " . $row["LastName"]. "</td><td> " . $row    ["DateReceived"]. "</td><td> " . $row["FinalReviewDate"]. "</td></tr>";
 }
 echo "</table>";
} else {
 echo "0 results";
}

$conn->close();
?> 

1 个答案:

答案 0 :(得分:1)

您可以为您和条件使用数组。但是一般来说,如果你要准备好语句和绑定值,你必须要小心。此外,您可以使用与以下类似的方式动态创建WHERE子句:

编辑:

$where = array(
    array(
        'column'=>'FinalReviewDate',
        'operator'=>'AND',
        'condition'=>'IS NOT NULL',
        'value'=>'',
    ),
    array(
        'column'=>'DateDelivered',
        'operator'=>'AND',
        'condition'=>'IS NULL',
        'value'=>'',
    ),
    array(
        'column'=>'DateAccepted',
        'operator'=>'AND',
        'condition'=>'IS NULL',
        'value'=>'',
    ),
    array(
        'column'=>'other_column',
        'operator'=>'OR',
        'condition'=>'>=',
        'value'=>5,
    ),
);

$temp = array();

foreach($where as $key => $value) {
if ($value['value'] == '') {
        $temp[] = $value['operator'].' '.$value['column'].' '.$value['condition'];
    } else {
        $temp[] = $value['operator'].' '.$value['column'].' '.$value['condition'].' '.$value['value'];
    }
}

$where_sql = '1 = 1 '.implode(' ', $temp);

echo $where_sql;

结果:

1 = 1 AND FinalReviewDate IS NOT NULL AND DateDelivered IS NULL AND DateAccepted IS NULL OR other_column >= 5

老答案

$ands = array(
    array(
        'column'=>'FinalReviewDate',
        'condition'=>'IS NOT NULL'
    ),
    array(
        'column'=>'DateDelivered',
        'condition'=>'IS NULL'
    ),
    array(
        'column'=>'DateAccepted',
        'condition'=>'IS NULL'
    ),
);

$temp = array();

foreach($ands as $key => $value) {
    $temp[] = $value['column'].' '.$value['condition'];
}

$and_sql = implode(' AND ', $temp);

echo $and_sql;

结果:

FinalReviewDate IS NOT NULL AND DateDelivered IS NULL AND DateAccepted IS NULL