因为我使用PHP连接到mysql数据库。我试图连接到数据库,同样我想在我单击表单上的登录按钮时将数据插入数据库。但是当我尝试这个代码时,没有显示db的更改,所以请任何帮助。谢谢..
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$conn = new PDO("mysql:host=$servername;dbname=Akalpa", $username, $password); // connection to my sql database
if(isset($_POST['Log In'])){
$username=$_POST['username'];
$query = "Insert into User(username) values('$username')"; //query to insert to db
if (mysql_query($query)) //checking the query
{
echo"<h3>Inserted Successfully</h3>"; //value inserted to db successfully
}
}
?>
答案 0 :(得分:2)
看起来好像在进行PDO连接,但使用的是mysql_函数。 您应该将代码写成这样的代码。
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$conn = new PDO("mysql:host=$servername;dbname=Akalpa", $username, $password); // connection to my sql database
if(isset($_POST['Log In'])){
$username=$_POST['username'];
$query = "INSERT INTO User(username) VALUES(:username)"; //query to insert to db
$stmt = $conn->prepare($query);
$result = $stmt->execute(["username"=>$username]);
if ($result) //checking the query
{
echo"<h3>Inserted Successfully</h3>"; //value inserted to db successfully
} else {
die("query failed");
}
}
?>
您的原始代码容易受到SQL注入,这并不好。我也不会推荐使用$ _POST [“Log In”],因为在数组键中包含空格是一种可怕的做法。尝试更简单的东西,例如“提交”或“登录”。