dongzipu7517 2019-04-03 21:58
浏览 649
已采纳

如何动态准备SQL查询(列名也),避免SQL注入

I recently learned about SQL Injection and the PHP recommendation to avoid it, using prepare() and bind_param(). Now, I want to prepare SQL queries dynamically, adding both column names and values.

I usted to do it like this, having the name field of the HTML input with the same name as the MySQL database column.

    <input type="text" name="firstname" >
    <input type="text" name="lastname" >

And the, create the SQL query dynamically using mysqli.

    // Extract values from POST
    $parameters = $_POST;
    // Organize the values in two strings
    foreach ($parameters as $id => $value) {
        $fields = $fields . "`" . $id . "`,";
        $values = $values . "'" . $value . "',"; 

        /*e.g.
            $fields = `firstname`,`lastname`
            $values = 'John','Wick'
        */
    }

    // Write into the database
    $sql = "INSERT INTO `user` ($fields) VALUES ($values)";

    /*e.g.
        INSERT INTO `user` (`firstname`,`lastname`) VALUES ('John','Wick')
    */

I would like to know if there is a way to do this using prepare() and bind_param() to avoid SQL injection, may be adding adding some data-type="s" to the HTML input tag or if there is a better, more best-practices, way to do it.

  • 写回答

2条回答 默认 最新

  • ds753947 2019-04-03 22:18
    关注

    You can use bound parameters only for an element that would be a constant value — a quoted string, a quoted datetime, or a numeric literal.

    You can't use a parameter placeholder for anything else in SQL, like column names, table names, lists of values, SQL keywords or expressions, or other syntax.

    If you need to make column names dynamic, the only option is to validate them against a list of known columns.

    $columns_in_user_table = [
      'userid'=>null,
      'username'=>'',
      'firstname'=>'',
      'lastname'=>''
    ];
    // Extract values from POST, but only those that match known columns
    $parameters = array_intersect_key($_POST, $columns_in_user_table);
    // Make sure no columns are missing; assign default values as needed
    $parameters = array_merge($columns_in_user_table, $parameters);
    

    If you use PDO instead of mysqli, you can skip the binding. Just use named parameters, and pass your associative array of column-value pairs directly to execute():

    $columns = [];
    $placeholders = [];
    foreach ($parameters as $col => $value) {
        $columns[] = "`$col`";
        $placeholders[] = ":$col";
    }
    $column_list = implode($columns, ',');
    $placeholder_list = implode($placeholders, ',');
    
    // Write into the database
    $sql = "INSERT INTO `user` ($column_list) VALUES ($placeholder_list)";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($parameters);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了