2012-04-18 30 views
-1

我試圖運行查詢來確定列A是否爲真。如果它是真的,則獲取不同列B的內容(可能數組用「,」分隔),並使用這些內容查詢不同的表。我的問題是,B列可能是一個數字或可能是10個數字全部由「,」分隔,我需要查詢第二個表的列查詢每個數字的前一個查詢。如果有人可以幫助那會很好。通過一個或多個數組值查詢表

編輯:我試圖使用數組explode函數,但無法弄清楚如何查詢下一個表來包含這些值。

我想象它是像

query = select * from table where location = arrayValue[1] or location = arrayValue[2] 
+0

爲什麼這是-1? – Rob 2012-04-18 18:05:52

回答

0

聖特爾莫·馬克斯的適應這裏,但改進:

<?php 
//Let's say $bcolumn is a string with the values of B column, separated by colons 
$bcolumnArray = explode(",", $bcolumn); 
array_walk($bcolumnArray, 'htmlentities'); 

//Build SQL query 
$SQL = 'SELECT * FROM table'; 
if(count($bcolumnArray)){ 
    $SQL.= ' WHERE IN ("'.implode('", "', $vbcolumnArray).'")'; 
} 

//Query your second table here 
$Qry = mysql_query($sql); 

// Results here : 
while($Res = mysql_fetch_assoc($Qry)){ 
    print_r($Res); 
} 
?> 

我建議PDO還...看看:PDO

+0

我是否運行foreach()來顯示結果? – Rob 2012-04-18 17:48:20

+0

看我的編輯..... – 2012-04-18 17:50:31

+0

我想感謝大家的幫助。 – Rob 2012-04-18 18:05:21

0

使用PHP的explode()功能,您的字符串轉換成一個數組。

<?php 
//Let's say $bcolumn is a string with the values of B column, separated by colons 
$bcolumnArray = explode(",", $bcolumn); 

//Build SQL query 
$sql = "SELECT * FROM table WHERE "; 
for($i=0; $i < count($bcolumnArray); $i++) 
{ 
    $sql .= "location = " . $value; 
    if($i != count($bcolumnArray)-1) 
    { 
     $sql .= " or "; 
    } 
} 

//Query your second table here 
mysql_query($sql); 
?> 

文檔:http://php.net/manual/en/function.explode.php

+0

對不起,只是編輯我的帖子。我需要查詢每個返回值的「位置」列。 – Rob 2012-04-18 16:33:40

+0

@Rob我編輯了我的答案。請注意我沒有真正測試這個代碼的錯誤。 – 2012-04-18 16:39:03

+0

您正在將'$ value'強制執行到SQL查詢中,並盲目執行它,這很容易受到SQL注入攻擊。 **不要這樣做**。如果你不知道如何逃避東西,請使用[PDO](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/)正常。在這種情況下,這些數字可能只是數字並不重要,因爲與其他數據一起重複是一種危險模式。這些數字可能會以HTTP參數的形式出現,您可以將其控制爲零。 – tadman 2012-04-18 16:49:28