2013-05-15 83 views
0

我有一個問題,用sql作爲值而不是名稱本身提取列名稱。顯示動態結果PHP mySQL

因此,例如,返回結果顯示

SELECT ll_project.project_id, ll_project.size, ll_lessons.lesson_title FROM ll_project INNER JOIN ll_lessons ON ll_project.project_id = ll_lessons.project_id WHERE ll_project.project_id = BSKYB5555 
Unknown column 'BSKYB5555' in 'where clause' 

從下面的代碼

$pid = $_POST['project_id'] ; 
$psize = $_POST['projectSize'] ; 
$pdepts = $_POST['depts'] ; 
$lstage = $_POST['stage'] ; 
$ltype = $_POST['type'] ; 
$impacted = $_POST['impacted'] ; 
//Your columns in the DB 
$columns = array('project_id'=>'ll_project.project_id','projectSize'=>'ll_project.size','depts'=>'ll_project.deptartment','stage'=>'ll_lessons.stage','type'=>'ll_lessons.type','impacted'=>'impacted'); 

$sqlString = null; 
echo "Total Number Of Captured Post Variables is:"; 
echo count($_POST); 
echo '<br />'; 

$number = 0; 
$queryStr = ""; 
$preStr = array(); 
foreach ($_POST as $key => $val) { 

if (!empty($_POST[$key])){ 
     if(!is_array($_POST[$key])) 
      $currentStr = $columns[$key]." = ".$val; 
     else 
     $currentStr = $columns[$key]." IN (".implode(',',$_POST[$key]).")"; 
     $preStr[] = $currentStr; 
    } 
} 
$queryStr = "SELECT ll_project.project_id, ll_project.size, ll_lessons.lesson_title FROM ll_project INNER JOIN ll_lessons ON ll_project.project_id = ll_lessons.project_id WHERE ".implode(' AND ',$preStr); 

echo $queryStr; 
echo '<br />'; 
if($number ==1) { 
}else{ 
} 

$result = mysql_query($queryStr) or die(mysql_error()); 
while($row = mysql_fetch_assoc($result)) { 
echo ' <tr> 
<td>'.$row['project_name'].' </td> 
<td>'.$row['project_id']. ''; 
} 

我在做什麼錯了,這是爲什麼拿起值作爲列名?

回答

4

添加在你的查詢值引號

SELECT ll_project.project_id, ll_project.size, ll_lessons.lesson_title FROM ll_project INNER JOIN ll_lessons ON ll_project.project_id = ll_lessons.project_id WHERE ll_project.project_id = "BSKYB5555" 

由於沒有報價,它不會把它作爲一個字符串

編輯

不幸的是,代碼和邏輯是有點難以請按照因爲沒有評論

您可以嘗試替換

$currentStr = $columns[$key]." = ".$val; 

$currentStr = $columns[$key]." = '".mysql_real_escape_string($val)."'"; 

這應該解決您的問題,並刪除SQL注入漏洞,你現在有直接在查詢中使用用戶輸入。

+0

你能告訴我一個例子?不確定報價應該在哪裏?好吧,我看到她生病嘗試 – Tazzy

+0

SELECT是從動態查詢生成的$ columns = array('project_id'=>'ll_project.project_id',etc ... 是否需要雙引號' project_id'? – Tazzy

+0

我最初並沒有寫信給查詢,它是從$ columns = array keys和values中的動態查詢中抓取的。 我沒有辦法將雙引號放在「Number」的周圍,如圖所示當從$ queryStr回聲; – Tazzy

0

如果您在查詢中使用字符串,你必須enclapse它

SELECT ll_project.project_id, ll_project.size, ll_lessons.lesson_title FROM ll_project INNER JOIN ll_lessons ON ll_project.project_id = ll_lessons.project_id WHERE ll_project.project_id = 'BSKYB5555'