MySql查询的动态while循环

时间:2013-01-04 04:06:47

标签: php mysql loops dynamic

如何缩短这个mysql查询以便在php中使用?

    <?php  
    $sql = "SELECT * FROM $this->usernameid where
    name LIKE '%$term%' OR
    manufacture1 LIKE '%$term%' OR
    manufacture2 LIKE '%$term%' OR
    manufacture3 LIKE '%$term%' OR
    manufacture4 LIKE '%$term%' OR
    manufacture5 LIKE '%$term%' OR
    manufacture6 LIKE '%$term%' OR
    manufacture7 LIKE '%$term%' OR
    manufacture8 LIKE '%$term%' OR
    manufacture9 LIKE '%$term%' OR
    manufacture10 LIKE '%$term%'
        ORDER BY $order1";
    ?>

想要做一个while循环,这里的例子是我的$ _POST,用于该程序的另一部分。

   <?php

    $i = 1;
    while ($i < 10) {
        $manufacture[$i] = strtoupper(filterinput($_POST['manufacture' . $i]));
        $i++;
    };
    ?>

1 个答案:

答案 0 :(得分:0)

// Base query
$baseQuery = "SELECT * FROM $this->usernameid WHERE name LIKE '%$term%' ";

// Get all columns from the table with manufacturers
$manufacturers = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA "
               . "WHERE TABLE_NAME = '{YOUR_TABLE}' "
               . "AND COLUMN_NAME LIKE 'manufacturer%';"
// Execute query
$getManufacturers = mysql_query( $manufacturers );
$addWhereClause = ''; // Additional WHERE clauses
// Loop over all the columns 'LIKE manufacturer%'
while ($manu = mysql_fetch_rows( $getManufacturers )) {
  // Add an additional clause for every manufacturer
  $addWhereClause .= "OR $manu LIKE '%$term% ";
}

// Append everything together and you have your dynamic query.
$query = $baseQuery.$addWhereClause."ORDER BY $order1;";