使用php简化可以有多个输入选项的MySQL查询

时间:2012-07-31 12:28:01

标签: php mysql

我有一个脚本将查询我的数据库,并且需要能够使用四个选项中的一个或全部进行查询。选项是start sku,end sku(这是一个选项,因为必须有一个搜索范围),创建者和创建日期。我知道我可以使用MANY if..elseif语句来做到这一点,但我必须认为有更好更简单的方法。这是我到目前为止的代码:

$start =mysql_real_escape_string ($_POST['skuStart']);
$end = mysql_real_escape_string($_POST['skuEnd']);
$source = mysql_real_escape_string($_POST['source']);
$processDate = mysql_real_escape_string($_POST['processDate']);

if(!empty($start) && !empty($end) && empty($source) && empty($processDate)){
$result = $conn->query("Select * from inventory where sku >= $start and sku <= $end");

 } elseif (empty($start) && empty($end) && !empty($source) && empty($processDate)){
$result = $conn->query("Select * from inventory where created_by = '$source'");

 } elseif (empty($start) && empty($end) && empty($source) && !empty($processDate)) {
$result = $conn->query("Select * from inventory where date_process = '$processDate'");

} elseif(!empty($start) && !empty($end) && !empty($source) && empty($processDate)){
$result = $conn->query("Select * from inventory where sku >= $start and sku <= $end and created_by = '$source'");

} else {
$result = $conn->query("Select * from inventory where sku >= '$start' and sku <= '$end' and created_by = '$source' and date_process = '$processDate'");
}

while($row = $result->fetch_assoc())
    {

        $skuArray[$x] = $row['sku'];
        $isbnArray[$x] = $row['isbn13'];
        $qtyArray[$x] = $row['quantity'];
        $defectArray[$x] = $row['defect_id'];
        $sourceArray[$x] = $row['source_id'];
        $featureArray[$x] = $row['feature_id'];
        $locationArray[$x] = $row['location_id'];
        $processDateArray[$x] = $row['date_process'];
        $bookTypeArray[$x] = $row['book_type_id'];
        $createdByArray[$x] = $row['created_by'];
        $modifiedByArray[$x] = $row['modified_by'];

        $x++;

这种非常粗糙的形式是有效的,但有没有办法让if elseif简化?

注意:我知道我应该使用PDO来阻止sql注入,但我还没有完全了解到,所以我正在使用它。

4 个答案:

答案 0 :(得分:2)

<?php
$db = new PDO('mysql:host=localhost;dbname=my_db', 'user', 'passwd');

$sql = "SELECT * FROM INVENTORY ";

$where  = array ();
$params = array ();
if (! empty($start) && ! empty($end) {
    $where[] = " sku >= :start AND sku <= :end ";
    $params['start'] = $start;
    $params['end']   = $end;
}
if (! empty($source)) {
    $where[] = " created_by = :source ";
    $params['source'] = $source;
}
if (! empty($processDate)) {
    $where[] = " date_process = :date_process ";
    $params['date_process'] = $processDate;
}

if (! empty($where)) {
    $sql .= ' WHERE ' . join (' AND ', $where);
}

$statement = $db->prepare($sql);
$statement->execute($params);

while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
   // ...
}

答案 1 :(得分:1)

$q = array();
if (!empty($start))
  $q[] = "sku >= '$start'";
if (!empty($end))
  $q[] = "sku <= '$end'";
#...
$q = join(') AND (', $q);
$q = "SELECT * FROM inventory WHERE ($q)";

或者你可以更进一步:

$params = array(
   'skuStart' => "sku >= '##'",
   'skuEnd' => "'sku <= '##'",
   #...
);

$q = array();
foreach($params as $k=>$sql) {
   $v = mysql_real_escape_string($_POST[$k]);
   if (!empty($v)) {
     $sql = tr_replace('##', $v, $sql);
     $q[] = $sql;
   }
}
$q = join(') AND (', $q);

然后你可以添加用于验证的类型,以及其他增强元数据和构建小框架的东西......

每当你觉得自己在重复自己时,你应该检查现有的解决方案(图书馆/框架)或建立你的解决方案...... DRY

答案 2 :(得分:1)

撇开您已经知道的问题 - 切换到PDO并使用绑定参数 - 您可以通过以下方式使代码更清晰:

<?php

$start          = mysql_real_escape_string ($_POST['skuStart']);
$end            = mysql_real_escape_string($_POST['skuEnd']);
$source         = mysql_real_escape_string($_POST['source']);
$processDate    = mysql_real_escape_string($_POST['processDate']);
$where          = array();

if(!empty($start))
{
    $where[] = 'sku >= ' . $start;
}

if(!empty($end))
{
    $where[] = 'sku <= ' . $end;
}

if(!empty($source))
{
    $where[] = 'created_by = \''.$source .'\'';
}

if(!empty($processDate))
{
    $where[] = 'date_process = \''.$processDate .'\'';
}

$query = 'SELECT * FROM inventory';

if(count($where))
{
    $query .= ' WHERE ' . implode(' AND ', $where);
}

$result = $conn->query($query);

while($row = $result->fetch_assoc())
    {

        $skuArray[$x] = $row['sku'];
        $isbnArray[$x] = $row['isbn13'];
        $qtyArray[$x] = $row['quantity'];
        $defectArray[$x] = $row['defect_id'];
        $sourceArray[$x] = $row['source_id'];
        $featureArray[$x] = $row['feature_id'];
        $locationArray[$x] = $row['location_id'];
        $processDateArray[$x] = $row['date_process'];
        $bookTypeArray[$x] = $row['book_type_id'];
        $createdByArray[$x] = $row['created_by'];
        $modifiedByArray[$x] = $row['modified_by'];

        $x++;

答案 3 :(得分:0)

您可以使用查询构建器。例如,如果您不使用任何框架,则https://github.com/jstayton/QueryBuilder(最初在谷歌成立)。