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 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测