【问题标题】:Insert Into with PDO使用 PDO 插入
【发布时间】:2020-06-25 22:18:29
【问题描述】:

我是 PHP、MySQL 和 PDO 的新手。 经过大量搜索,我编写了这段代码来插入带有密码的新用户/客户。

<?php
require_once '../../src/mysql/dbconfig.php';

try
  {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    echo "Connected to $dbname at $host successfully.";
  } 
  catch (PDOException $pe) 
 {
   die("Could not connect to the database $dbname :" . $pe->getMessage());
 }

$stmt = $conn -> prepare($sql);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt -> bindValue(":email", $email);
$stmt -> bindValue(":password", $password);

$sql = "INSERT INTO customer (email, password) VALUES (:email, SHA2(:password,512))";

$stmt -> execute();
$conn = null;

?>

<html>
<body>

Welcome <?php echo $_POST["email"]; ?><br>
Your password is: <?php echo $_POST["password"]; ?>

</body>
</html>

当我提交时,转到另一个 PHP 页面,说出用户的电子邮件和密码。 所以当我执行 SELECT * FROM 时,我收到一个空的 SET。

(基本上Insert不起作用,但是在PHP页面上,它说的是INSERT中插入的信息)

我做错了什么?

【问题讨论】:

  • 将 $sql 上移几行,在准备语句之前

标签: php mysql pdo


【解决方案1】:

基本上,我做错的是在其值之后调用语句。

<?php
 require_once '../../src/mysql/dbconfig.php';

 try
 {
   $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
   echo "Connected to $dbname at $host successfully.";
 } 
 catch (PDOException $pe) 
{
 die("Could not connect to the database $dbname :" . $pe->getMessage());
}

$sql = "INSERT INTO customer (email, password) VALUES (:email,  SHA2(:password,512))";

 $stmt = $conn -> prepare($sql);
 $email = $_POST['email'];
 $password = $_POST['password'];
 $stmt -> bindValue(":email", $email);
 $stmt -> bindValue(":password", $password);

$stmt -> execute();
$conn = null;

?>

【讨论】:

    猜你喜欢
    • 2014-05-06
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2014-01-25
    • 2013-01-28
    • 2019-07-15
    • 2015-08-20
    相关资源
    最近更新 更多