所以我一直在尝试创建一个简单的HTML表单,将用户信息提交给本地MYSQL数据库。当我尝试运行它时,我得到"不能POST /test/addperson.php"。我已经尝试了许多其他解决方案,但似乎没有一个解决方案。
HTML
<!DOCTYPE html>
<html>
<body>
<h2>User Database</h2>
<br>
<form action="test/addperson.php" method="post">
<p>First Name: </p>
<input type="text" name="first_name">
<p>Last Name: </p>
<input type="text" name="last_name"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
PHP
<?php
$connect = mysql_connect("localhost:3306","root", "password");
if(!connect){
die('Connection Failed: ' . mysql_error());
}
mysql_select_db("Users", $connect);
$user_info = "INSERT INTO employees (first_name, last_name) VALUES ('$_POST[first_name]', '$_POST[last_name]')";
if(!sql_query($user_info, $connect)){
die('Error' . mysql_error());
}
echo "Your information was added to the database.";
mysql_close($connect);
?>
答案 0 :(得分:0)
使用这样的预备语句。出于安全原因,请勿使用MYSQL_函数。 如果是简单页面,请使用此代码。只需创建一个php页面并粘贴以下代码即可。
<?php
$servername = "yourservername";
$username = "root";
$password = "yourpassword";
try
{
$conn = new PDO("mysql:host=$servername;dbname=yourdatabse",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
//a little protection
$first_name=htmlentities( $first_name, ENT_QUOTES | ENT_HTML5,
$encoding = 'UTF-8' );
$last_name=htmlentities( $last_name, ENT_QUOTES | ENT_HTML5,
$encoding = 'UTF-8' );
//save to database
$query = 'INSERT INTO employees (first_name, last_name) VALUES
(:name,:lastname)';
$st=$conn->prepare($query);
$st->bindParam(':name', $first_name);
$st->bindParam(':lastname', $last_name);
$st->execute();
$st->CloseCursor();
$st=null;
}
?>
<!DOCTYPE html>
<html>
<body>
<h2>User Database</h2> <br>
<form action="" method="post">
<p>First Name: </p>
<input type="text" name="first_name">
<p>Last Name: </p>
<input type="text" name="last_name"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
答案 1 :(得分:0)
您需要稍微更改一下代码并在插入查询中添加引号:
$user_info = "INSERT INTO employees (first_name, last_name) VALUES ('".$_POST['first_name']."', '".$_POST['last_name']."')";
但与其他人一样,有更好的方法可以做到这一点,准备好的陈述等。