douguangxiang0363 2014-11-19 17:33
浏览 24

在php中看似相同的sql查询,但是一个插入额外的行

I generate the below query in two ways, but use the same function to insert into the database:

INSERT INTO person VALUES('','john', 'smith','new york', 'NY', '123456');

The below method results in CORRECT inserts, with no extra blank row in the sql database

foreach($_POST as $item) 
$statement .= "'$item', ";

$size = count($statement);
$statement = substr($statement, 0, $size-3);
$statement .= ");";

The code below should be generating an identical query to the one above (they echo identically), but when I use it, an extra blank row (with an id) is inserted into the database, after the correct row with data. so two rows are inserted each time.

$mytest = "INSERT INTO person VALUES('','$_POST[name]', '$_POST[address]','$_POST[city]', '$_POST[state]', '$_POST[zip]');";

Because I need to run validations on posted items from the form, and need to do some manipulations before storing it into the database, I need to be able to use the second query method.

I can't understand how the two could be different. I'm using the exact same functions to connect and insert into the database, so the problem can't be there.

below is my insert function for reference:

function do_insertion($query) {      
    $db = get_db_connection();
        if(!($result = mysqli_query($db, $query))) {
            #die('SQL ERROR: '. mysqli_error($db));
             write_error_page(mysqli_error($db));
          } #end if     
    }

Thank you for any insite/help on this.

  • 写回答

2条回答 默认 最新

  • doubang9906 2014-11-19 17:52
    关注

    Using your $_POST directly in your query is opening you up to a lot of bad things, it's just bad practice. You should at least do something to clean your data before going to your database.

    The $_POST variable often times can contain additional values depending on the browser, form submit. Have you tried doing a null/empty check in your foreach?

    !~ Pseudo Code DO NOT USE IN PRODUCTION ~!

    foreach($_POST as $item) 
    {
    
        if(isset($item) && $item != "")
        {   
            $statement .= "'$item', ";
    
            $size = count($statement);
            $statement = substr($statement, 0, $size-3);
            $statement .= ");";
         }
    
    }
    

    Please read @tadman's comment about using bind_param and protecting yourself against SQL injection. For the sake of answering your question it's likely your $_POST contains empty data that is being put into your query and resulting in the added row.

    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么