将表单数据插入mysql表中(安全)

时间:2018-09-28 03:12:23

标签: php mysql database mysqli

这是编辑后的代码?我仍然收到404错误,并且什么都没有发送到数据库表。提交表单后404页面上的网址后,我看到dbhh.php(以下文件)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // prepare sql and bind parameters
    $stmt = $conn->prepare("INSERT INTO user_input(first_name1, last_name1, email1) 
    VALUES (:first_name1, :last_name1, :email1)");

    // insert a row

    $stmt->execute([
    ':first_name1' => $_POST["first_name1"],
    ':last_name1'  => $_POST["last_name1"],
    ':email1'      => $_POST["email1"]
]);

        echo "New records created successfully";
    }
catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
$conn = null;

?> 

3 个答案:

答案 0 :(得分:1)

准备查询后,您已声明POST变量。首先,请确保将POST值分配给变量。

// insert a row
$first_name1 = $_POST["first_name1"];
$last_name1 = $_POST["last_name1"];
$email1 = $_POST["email1"];

$stmt = $conn->prepare("INSERT INTO user_input(first_name1, last_name1, email1) 
VALUES (:first_name1, :last_name1, :email1)");
$stmt->bindParam(':first_name1', $first_name1);
$stmt->bindParam(':last_name1', $last_name1);
$stmt->bindParam(':email1', $email1);
$stmt->execute();

注意区别。我将POST放在查询之前。 bindParam执行后,就可以获取值。

答案 1 :(得分:0)

什么@david said。尽管更紧凑的方法是跳过手动绑定,并立即按PDO::execute传递参数:

$stmt->execute([
    ':first_name1' => $_POST["first_name1"],
    ':last_name1'  => $_POST["last_name1"],
    ':email1'      => $_POST["email1"]
]);

答案 2 :(得分:0)

尝试一下。希望对您有帮助。

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

$conn = new mysqli($servername, $username, $password, $dbname);
 $stmt = $mysqli->prepare("INSERT INTO user_input (first_name1, last_name1,email1) VALUES (?, ?)");
$stmt->bind_param("si", $_POST['first_name1'], $_POST['last_name1'],$_POST['email1']);
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();

?>