如何从sql注入中保护我的反馈表?

时间:2018-05-11 21:06:13

标签: php mysql

我是php的完全初学者。我的代码有一个反馈表单,可以将数据发送到mysql。我不确定如何防止SQL注入。我很乐意帮助你。

以下是代码:

  <?php
    if(isset($_POST["send_message"])){
      $hostname='localhost';
      $username='';
      $password='';

      try {
        $dbh = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
        $message = $_POST['message'];
        $sql = "INSERT INTO tbl_contact (message) VALUES ('$message')";

        if ($dbh->query($sql)) {
          include "thanks.php";
        } else{
          echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
        }

        $dbh = null;
      } catch(PDOException $e) {
        echo $e->getMessage();
      }
    }
?>

更新: 我尝试使用预准备语句并绑定参数,但我得到了: 未捕获的错误:调用未定义的方法PDOStatement :: bind_param()。

以下是更新后的代码:

<?php
if(isset($_POST["send_message"])){
    $dbConnection = new PDO('mysql:dbname=sondagg9_submit;host=localhost;charset=utf8', 'sondagg9_travadm', 'Mc%F}SrGk5m5#t<Crb4?');
    $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbConnection->prepare('INSERT INTO tbl_contact (message) VALUES (?)');
    $stmt->bind_param('s', $message);
    $message = $_POST['message'];
    $stmt->execute();
    $result = $stmt->get_result();
    }
?>

解决: 感谢您的评论,我已经能够以这种方式解决问题:

<?php
if(isset($_POST["send_message"])){
    $dbConnection = new PDO('mysql:dbname=sondagg9_submit;host=localhost;charset=utf8', 'sondagg9_travadm', 'Mc%F}SrGk5m5#t<Crb4?');
    $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $message = $_POST['message'];
    $stmt = $dbConnection->prepare('INSERT INTO tbl_contact (message) VALUES (:message)');
    $stmt->execute([ 'message' => $_POST['message'] ]);
    }
?>

0 个答案:

没有答案