【问题标题】:Dynamic while loop for MySql queryMySql 查询的动态 while 循环
【发布时间】:2013-01-04 12:32:34
【问题描述】:

如何缩短这个 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++;
    };
    ?>

【问题讨论】:

  • 有什么理由为每个制造商提供一个专栏?
  • 不是针对“每个”制造商,而是针对制造商组。

标签: php mysql loops dynamic


【解决方案1】:
// 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;";

【讨论】:

猜你喜欢
  • 2013-03-11
  • 2023-03-30
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 2013-11-23
相关资源
最近更新 更多