2013-01-04 86 views
0

我將如何縮短這個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

它不是針對「每個」製造商,而是製造商小組。 –

回答

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://stackoverflow.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://stackoverflow.com/a/14117228/1762224) –