gpt4 book ai didi

php - 使用PHP错误将HTML表单中的数据输入到MYSQL

转载 作者:行者123 更新时间:2023-11-30 23:45:18 25 4
gpt4 key购买 nike

我在使用 PHP 将数据从表单输入到 MYSQL 数据库时遇到了一些问题。下面我已经包含了这些文件,我只想提一下我之前通过更改值输入了数据:

VALUES ('Jake', 'Doe', 'john@example.com')";

而且有效。

索引.php

    <?php include 'assets/header.php';$title='Home Page';?> 
<div class="context">
<form action="connect_to_mysql.php" method="post">
<label>First Name:</label>
<input type="text" name="first_name" id="fist_name" required="required" placeholder="Please Enter First Name"/><br /><br />
<label>Last Name:</label>
<input type="text" name="last_name" id="last_name" required="required" placeholder="Please Enter Your Last Name"/><br/><br />
<label>Email:</label>
<input type="email" name="email" id="email" required="required" placeholder="Please Enter Your Email"/><br/><br />
<input type="submit">
</form>

</div>
<?php include 'assets/footer.php';?>

connect_to_mysql.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$email = mysql_real_escape_string($_POST['email']);

$sql = "INSERT INTO hello_world (firstname, lastname, email)
VALUES ('.$first_name', '.$last_name', '.$email')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>

错误:

Fatal error: Uncaught Error: Call to undefined function mysql_real_escape_string() in E:\XAMPP\htdocs\mysql\connect_to_mysql.php:14 Stack trace: #0 {main} thrown in E:\XAMPP\htdocs\mysql\connect_to_mysql.php on line 14

最佳答案

使用此代码并检查错误是否仍然出现注意:此代码通过 PDO 类连接

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new PDO('mysql:host='.$servername.';dbname='.$dbname.';', $username, $password);

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$email = mysql_real_escape_string($_POST['email']);

$sql = $conn->prepare("
INSERT INTO hello_world(first_name, lastname, email)
VALUES (:firstname, :lastname, :email)
");
$sql->execute([
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $email
]);

if ($sql->rowCount() > 0) {
echo "New record created successfully";
}
else
{
//error message
}

?>

关于php - 使用PHP错误将HTML表单中的数据输入到MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41680452/

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