使用PDO编号与字符串

时间:2015-03-04 21:04:16

标签: php mysql pdo

我有以下PHP代码:

$comp1 = $_POST['cohort_id1'];
$comp2 = $_POST['cohort_id2'];
$comp3 = $_POST['cohort_id1'];
$comp4 = $_POST['cohort_id2'];

$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "SELECT cat_code, value, :comp1 , :comp2, round(:comp3/:comp4 * 100) as index_number FROM {$table}";
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY) );
$stmt->execute(array(':comp1' => $comp1, ':comp2' => $comp2, ':comp3' => $comp3, ':comp4' => $comp4 ));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($result);

以下是其中一个对象的返回方式:

?: "national_percent"
cat_code: "edu"
index_number: null
value: "Some College"

我无法理解的是为什么第一行返回“?”,但更重要的是,为什么index_number为空。我怀疑是因为这些值被转换为字符串,但我不知道如何处理它。

1 个答案:

答案 0 :(得分:1)

要防止SQL注入包含列名的用户输入,请根据有效列名数组检查输入:

$valid_columns = array('col1', 'col2', 'col3');
if (in_array($user_input_col, $valid_columns)) 
{
  $sql = "SELECT {$user_input_col} from table...";
  ...
}
else
{
     die('Invalid column name');
}