PHP 无法使用 PDO 将数据插入数据库
PHP Unable to insert data into database using PDO
我想将用户提供的数据插入到数据库中,当我使用简单的 mysqli 时,它工作得很好,但是当我使用 PDO 时,数据被插入到数据库中。
<?php
$server = 'localhost';
$username = 'root';
$pass = '';
$database = 'db';
try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$name = '';
$password = '';
$email = '';
$uid = '';
$sql = "INSERT INTO users(name,email,password,userid) VALUES(?,?,?, ?)";
if (isset($_POST['username'])) {
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$newpass = hash("sha256", $password);
if ($name != '' && $password != '' && $email != '') {
$insertUser = $conn->prepare($sql);
$insertUser->execute($name, $email, $password, $uid);
}
}
$conn = null;
只需使用参数数组:
$sql = "INSERT INTO users(name,email,password,userid) VALUES(?, ?, ?, ?)";
if(isset($_POST['username']))
{
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$newpass = hash("sha256", $password);
if($name!='' && $password!='' && $email!='')
{
$insertUser = $conn->prepare($sql);
// use ARRAY instead plain variables
$insertUser->execute([$name, $email, $password, $uid]);
}
}
我想将用户提供的数据插入到数据库中,当我使用简单的 mysqli 时,它工作得很好,但是当我使用 PDO 时,数据被插入到数据库中。
<?php
$server = 'localhost';
$username = 'root';
$pass = '';
$database = 'db';
try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$name = '';
$password = '';
$email = '';
$uid = '';
$sql = "INSERT INTO users(name,email,password,userid) VALUES(?,?,?, ?)";
if (isset($_POST['username'])) {
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$newpass = hash("sha256", $password);
if ($name != '' && $password != '' && $email != '') {
$insertUser = $conn->prepare($sql);
$insertUser->execute($name, $email, $password, $uid);
}
}
$conn = null;
只需使用参数数组:
$sql = "INSERT INTO users(name,email,password,userid) VALUES(?, ?, ?, ?)";
if(isset($_POST['username']))
{
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$newpass = hash("sha256", $password);
if($name!='' && $password!='' && $email!='')
{
$insertUser = $conn->prepare($sql);
// use ARRAY instead plain variables
$insertUser->execute([$name, $email, $password, $uid]);
}
}