0

我在 sql 将列名作为值而不是名称本身时遇到问题。

因此,例如返回的结果显示

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

2 回答 2

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 注入漏洞。

于 2013-05-15T08:15:52.790 回答
0

如果在查询中使用字符串,则必须包含它

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'
于 2013-05-15T08:16:41.043 回答