2013-03-23 93 views
-2

我是新來的PHP,並試圖動態地創建一個查詢。這是我得到foreach語法錯誤的一段代碼。可以請你幫我修復這個bug嗎?foreach內mysql查詢

$select = "SELECT pmid FROM articles WHERE pmid IN 
(" 
    foreach($results as $result) { 
     $select .= $result['pmid'] . ','; 
    } 
    $select = trim($select,','); . 
") 
      "; 

回答

0
$pmids = array(); 
foreach($results as $result) { 
    $pmids[] = $result['pmid']; 
} 

if (!empty($pmids)) { 
    $select = 'SELECT pmid FROM articles WHERE pmid IN (' . join(',',$pmids) . ')'; 
} else { 
    $select = 'SELECT pmid FROM articles WHERE 1 = 0'; 
} 

你必須確保該$result['pmid']值是安全,可以在數據庫查詢字面上月底缺少分號。

0

您沒有使用書面方式SQL查詢的正確方式..

寫正確

foreach($results as $result) { 
    $select .= $result['pmid'] . ','; 
} 
$select = trim($select,','); 

$query = "SELECT pmid FROM articles WHERE pmid IN ($select)"; 
0

對此

$results = array(1,5,6,7); 
$select = "SELECT pmid FROM articles WHERE pmid IN (".implode(",", $results).")"; 
echo $select; 
看看