dongxie3352 2012-07-08 23:22
浏览 57
已采纳

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

I have a variable ($q=$_GET["q"];) that I want to run my prepared statement with. It contains a column name of my database table.

The value of the variable comes from a dropdown list. When I run the following code the output is the exact value that was chosen in the list. So it is just a column name.

$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>";

However, When I change this line $sql = "SELECT DISTINCT ? FROM repertoire";

to $sql = "SELECT DISTINCT ".$q." FROM repertoire"; the I get the desired rows from the database...

I'm not so good with PHP, so I guess that my syntax is wrong somewhere.

Thank you in advance for your help.

  • 写回答

1条回答 默认 最新

  • dongyan5815 2012-07-08 23:25
    关注

    In PDO, prepared statements prepare the values, not the tables.

    You'll need to handle the user input and quote directly.

    $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>";
    }
    

    Also read: Can PHP PDO Statements accept the table or column name as parameter?

    Edit: I've added a way to check to make sure $q is a valid column by basically doing a SQL desc in order to get all the column names out of table repertoire.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建