动态while循环MySql查询

问题描述:

我将如何缩短这个MySQL查询在PHP中的使用?动态while循环MySql查询

<?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++; 
    }; 
    ?> 
+2

任何原因,你必须为每个制造商列? – Kermit

+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;"; 
+0

[**请勿在新代码**中使用'mysql_ *'函数](http://*.com/a/14110189/1723893)。他们不再被维护[并被正式弃用](https://wiki.php.net/rfc/mysql_deprecation)。看到[**红框**](http://j.mp/Te9zIL)?学习[*准备的语句*](http://j.mp/T9hLWi),并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [这篇文章](http://j.mp/QEx8IB)将帮助你决定哪个。如果你选择PDO,[这里是一个很好的教程](http://j.mp/PoWehJ)。 –

+0

我知道他们已被弃用,但我真的只是将它们用于概念证明。这是我的答案中的2个查询字符串,真的很重要。其余的可以是OP的练习。我知道如何使用msqli我现在太累了,现在就想想。 [这是我使用mysqli回复的答案](http://*.com/a/14117228/1762224) –