使用php连接和插入Mysql数据库
因为我正在使用PHP连接mysql数据库。我尝试连接到数据库,同样,每当我单击表单上的“登录”按钮时,我都希望将数据插入数据库。但是当我尝试这段代码时,没有显示任何更改,所以请提供任何帮助。谢谢使用php连接和插入Mysql数据库,php,mysql,Php,Mysql,因为我正在使用PHP连接mysql数据库。我尝试连接到数据库,同样,每当我单击表单上的“登录”按钮时,我都希望将数据插入数据库。但是当我尝试这段代码时,没有显示任何更改,所以请提供任何帮助。谢谢 <?php $servername = "localhost"; $username = "root"; $password = "password"; $conn = new PDO("mysql:host=$servername
<?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
}
}
?>
看起来好像您正在进行PDO连接,但使用的是mysql_uu2;函数。
您应该让您的代码像这样编写
<?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[“登录”],因为在数组键中使用空格是一种可怕的做法。尝试一些简单的方法,例如“提交”或“登录” 只需将mysql\u query($query)
替换为$conn->query($query)
,然后看看jackm的答案,因为为了安全起见,你应该做更多的工作。