PDO - Prepared语句不处理变量权限

时间:2012-07-08 23:22:03

标签: php mysql variables pdo prepared-statement

我有一个变量($q=$_GET["q"];),我想用它来运行我准备好的语句。它包含我的数据库表的列名。

变量的值来自下拉列表。当我运行以下代码时,输​​出是在列表中选择的精确值。所以它只是一个列名。

$q=$_GET["q"];

$dsn = "mysql:host=$host;port=$port;dbname=$database";

$db = new PDO($dsn, $username, $password);

$sql = "SELECT DISTINCT ? FROM repertoire";
$stmt = $db->prepare($sql);
$stmt->execute(array($q));

    echo "<select>";
    while ( $row = $stmt->fetchObject() ) {
        echo "<option>";
        echo "{$row->{$q}}";
        echo "</option>";
        }
    echo "</select>";

但是,当我更改此行$sql = "SELECT DISTINCT ? FROM repertoire";

$sql = "SELECT DISTINCT ".$q." FROM repertoire";我从数据库中获得所需的行...

我对PHP不太满意,所以我猜我的语法在某处错了。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

在PDO中,准备好的语句准备值,而不是表格。

您需要直接处理用户输入和引用。

$q=$_GET["q"];

// Make sure you sanitize your user inputs using filter_inputs() or similar.

$dsn = "mysql:host=$host;port=$port;dbname=$database";

$colNames = new PDO($dsn, $username, $password); // Create object for getting column names.
$sql = "DESC repertoire Field"; // SQL for getting column names.
$stmt = $colNames->prepare($sql);
$stmt->execute();

$colList = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); // Fetch the results into $colList array.

if (in_array($q, $colList)) { // If the value of $q is inside array $colList, then run.

    $db = new PDO($dsn, $username, $password);

    $sql = "SELECT DISTINCT $q FROM repertoire";
    $stmt = $db->prepare($sql);
    $stmt->execute(array($q));

        echo "<select>";
        while ( $row = $stmt->fetchObject() ) {
            echo "<option>";
            echo "{$row->{$q}}";
            echo "</option>";
            }
        echo "</select>";
}

另请阅读:Can PHP PDO Statements accept the table or column name as parameter?

编辑:我添加了一种检查方法,通过基本上执行SQL desc来确保$ q是一个有效的列,以便从表格中获取所有列名。