如何使用准备好的语句将表单数据插入 PDO?

Posted

技术标签:

【中文标题】如何使用准备好的语句将表单数据插入 PDO?【英文标题】:How to insert form data into PDO using prepared statements? 【发布时间】:2017-11-29 23:47:42 【问题描述】:

所以我从 w3schools 学到了这一点。 . .然而,该示例使用直接注入代码的数据。我想知道如何使用相同的代码块而不是从表单接收数据

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

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 MyGuests (firstname, lastname, 
email) 
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);

// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

// insert another row
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

echo "New records created successfully";

catch(PDOException $e)

echo "Error: " . $e->getMessage();

$conn = null;
?>

【问题讨论】:

"John"换成表单值,可能是$_POST['firstname']? @chris85 谢谢!短而甜 【参考方案1】:

我认为你需要先学习PHP Form Handling

例如 make form.html

<html>
<body>

<form action="insert.php" method="post">
Name: <input type="text" name="firstname"><br>
Name: <input type="text" name="lastname"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

然后将数据处理到数据库 make insert.php

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

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 MyGuests (firstname, lastname, 
email) 
VALUES (:firstname, :lastname, :email)");
    $stmt->bindParam(':firstname', $firstname);
    $stmt->bindParam(':lastname', $lastname);
    $stmt->bindParam(':email', $email);

// insert a row
    $firstname = $_POST["firstname"];
    $lastname = $_POST["lastname"];
    $email = $_POST["email"];
    $stmt->execute();


    echo "New records created successfully";

catch(PDOException $e)

    echo "Error: " . $e->getMessage();

$conn = null;
?>

【讨论】:

以上是关于如何使用准备好的语句将表单数据插入 PDO?的主要内容,如果未能解决你的问题,请参考以下文章

PDO - 使用准备好的语句将所有 sql 数据放入 html 表中

无法使用 php 的 PDO 将数据插入数据库

使用 PDO 准备好的语句插入致命错误 [重复]

如何将 pdo 的准备好的语句用于 order by 和 limit 子句?

如何查看准备好的 PDO SQL 语句 [重复]

在 PHP 中到处使用准备好的语句? (PDO)