douliaodan2738 2012-03-05 23:44
浏览 67
已采纳

MySQL使用$ _REQUEST获取值后插入NULL值

I have input fields, but if the users leave it blank, i want to insert a null value to my database.

I request values like this:

$val1 = htmlspecialchars($_REQUEST["val"], ENT_QUOTES);

And then insert them to the DB:

INSERT INTO `table` ( `val1` , `val2` , `val3`) 
VALUES ('$val1', '$val2', '$val3');

I have tried removing the ' around val1, val2, val3 - but then nothing gets inserted into the DB if there is no value. I have also tried something like this:

if (!empty($val1)) {
$val1 = "'".$val1."'";
} else {
$val1 = NULL;}

And then without the ' around the values - still no insert to the DB

  • 写回答

4条回答 默认 最新

  • dongxieyi9115 2012-03-05 23:51
    关注

    Ok, first this

    INSERT INTO table ( val1 , val2 , val3) VALUES ('val1', 'val2', 'val3');

    will only ever insert the literal values "val1", "val2" and "val3". You aren't using any PHP variables.

    Secondly, use prepared statements and parameter binding to perform your queries to protect yourself from SQL injection. For example, using PDO

    $pdo = new PDO(/* DSN, username and password, just read the docs */);
    
    $stmt = $pdo->prepare('INSERT INTO table (val1, val2, val3) VALUES (?, ?, ?)');
    
    $params = array(
        isset($_REQUEST['val1']) ? $_REQUEST['val1'] : null,
        isset($_REQUEST['val2']) ? $_REQUEST['val2'] : null,
        isset($_REQUEST['val3']) ? $_REQUEST['val3'] : null
    );
    
    $stmt->execute($params);
    

    Also, you shouldn't HTML encode values going into a database. Perform the encoding when you display the value in an HTML document.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改