试图阻止SQL注入

时间:2013-08-28 18:22:15

标签: php sql mysqli sql-injection code-injection

我设置了一个下拉框,允许用户选择经济数据的要求。我试图通过使用mysqli来防止sql注入,但我没有运气。这是我的代码:

$gYear = $_POST["year"];
$gYear2 = $_POST["year2"];
$gMonth = $_POST["month"];
$gSelect = $_POST["location"];

switch($_POST['location']){
case "loc1":
$column = "Fayette";
break;

case "loc2":
$column = "Henry";
break;

case "loc3":
$column = "Randolph";
break;
case "loc4":
$column = "Rush";
break;

case "loc5":
$column = "Union";
break;

case "loc6":
$column = "Wayne";
break;

case "loc7":
$column = "INCounties";
break;

case "loc8":
$column = "Indiana";
break;

case "loc9":
$column = "Butler";
break;

case "loc10":
$column = "Darke";
break;

case "loc11":
$column = "Mercer";
break;

case "loc12":
$column = "Preble";
break;

case "loc13":
$column = "OHCounties";
break;

case "loc14":
$column = "Ohio";
break;

case "loc15":
$column = "US";
break;
}

$query = $conn->prepare("SELECT $column, Year, Month, FROM unemployed WHERE year BETWEEN ? AND ? and month= ?");

$query->bind_param('s', $gyear, $gYear2, $gMonth);

$query->execute(); 
$result = $query->get_result();

echo"<table>";
echo "<tr><th>Year</th><th>Month</th><th>$column</th></tr>";

while ($row = $result->fetch_assoc()){

echo "<tr><td>";
echo $row->$column;
echo "</td><td>";
echo $row->Year;
echo "</td><td>";
echo $row->Month;
echo "</td></tr>";

}

$query->close();



echo "</table";

}

这对我不起作用。我被困在这一段时间了。你知道我的代码的哪些部分有问题吗?我使用的是PHP 5.3.26。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:-1)

试试这个:

$query = $conn->prepare("SELECT `".$column."`, `Year`, `Month` FROM `unemployed` WHERE `Year` BETWEEN ? AND ? AND `Month`= ?");

请记住在列名和表名之前和之后添加反引号。此外,请记住将cAsE与它们在数据库中的显示方式相匹配。我也会将BETWEEN语法更改为更多或更少的选项,因为我认为你可能会缺少括号。

WHERE `YEAR` > ? AND `YEAR` <= ? AND `Month` = ?