我正在尝试使用PHP将值简单地插入数据库表中。但是每次所有预插入的值都会被擦除,并且不会插入任何值。
<?php
$servername = "localhost";
$username = "root";
$password = "rex";
$dbname = "test";
$usr = $_POST["Username"];
$pass = $_POST["password"];
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);
$sql = "INSERT INTO users(username,password)VALUES('$usr','$pass')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
答案 0 :(得分:0)
这应该有效:
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
$prepared = $conn->prepare($sql);
$prepared->execute([$usr, $pass]);
这也更好,因为您要绑定变量。
http://php.net/manual/en/pdo.prepare.php
您还应该清理$_POST
变量。用户名在$_POST
变量中还用大写U 拼写。
答案 1 :(得分:0)
mysql
中的访问控制内容上使用直接DML语句。而是使用CREATE USER
,GRANT
等FLUSH PRIVILEGES
才能使其生效。