gpt4 book ai didi

php - HTML 表单发送到 MYSQL DB 时出现 PHP POST 错误

转载 作者:行者123 更新时间:2023-11-29 18:38:51 25 4
gpt4 key购买 nike

所以我一直在尝试创建一个简单的 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);

?>

最佳答案

使用这样的准备好的语句。出于安全原因,请勿使用 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>

关于php - HTML 表单发送到 MYSQL DB 时出现 PHP POST 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com