使用 Mysqli_real_escape_string 处理表单数据
本文将教你使用 mysqli_real_escape_string
处理表单数据。
首先,我们将设置一个示例数据库和一个表。然后我们将创建一个接受用户输入的 HTML 表单。
之后,在 PHP 中,我们将解释如何使用 mysqli_real_escape_string
而不会导致错误。
设置本地服务器
本文的所有代码都将在服务器上运行。因此,如果你可以访问实时服务器,则可以跳过本节并继续下一节。
如果没有,请安装一个本地服务器,例如来自 Apache Friends 的 XAMPP。安装 XAMPP 后,找到 htdocs
文件夹并创建一个文件夹。
此文件夹将存储本文的所有代码。
创建数据库和表
在 XAMPP 中,你可以使用 phpMyAdmin
或命令行创建数据库。如果你在命令行上,请使用以下命令登录 MySQL:
#login to mysql
mysql -u root -p
登录 MySQL 后,创建一个数据库。在本文中,我们将数据库称为 my_details
。
CREATE database my_details
创建数据库后,使用下一个 SQL 代码创建一个表。该表将保存我们示例项目的数据。
CREATE TABLE bio_data (
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
PRIMARY KEY (id)) ENGINE = InnoDB;
创建 HTML 表单
HTML 表单将有两个表单输入。第一个收集用户的名字,第二个收集姓氏。
<head>
<meta charset="utf-8">
<title>Process Form With mysqli_real_escape_string</title>
<style>
body {
display: grid;
justify-content: center;
align-items: center;
height: 100vh;
}
</style>
</head>
<body>
<main>
<form action="process_form.php" method="post">
<label id="first_name">First Name</label>
<input id="first_name" type="text" name="first_name" required>
<label id="last_name">Last Name</label>
<input id="last_name" type="text" name="last_name" required>
<input type="submit" name="submit_form" value="Submit Form">
</form>
</main>
</body>
输出:
处理表格数据
在表单处理期间,我们使用 mysqli_real_escape_string
来转义表单输入。更重要的是,数据库连接应该是 mysqli_real_escape_string
的第一个参数。
因此,我们在下面的名字和姓氏上使用了 mysqli_real_escape_string
。要使用该代码,请将其保存为 process_form.php
。
<?php
if (isset($_POST['submit_form']) && isset($_POST["first_name"]) && isset($_POST["last_name"])) {
// Set up a database connection.
// Here, our password is empty
$connection_string = new mysqli("localhost", "root", "", "my_details");
// Escape the first name and last name using
// mysqli_real_escape_string function. Meanwhile,
// the first parameter to the function should
// be the database connection. If you omit, the
// database connection, you'll get an error.
$first_name = mysqli_real_escape_string($connection_string, trim(htmlentities($_POST['first_name'])));
$last_name = mysqli_real_escape_string($connection_string, trim(htmlentities($_POST['last_name'])));
// If there is a connection error, notify
// the user, and Kill the script.
if ($connection_string->connect_error) {
echo "Failed to connect to Database. Please, check your connection details.";
exit();
}
// Check string length, empty strings and
// non-alphanumeric characters.
if ( $first_name === "" || !ctype_alnum($first_name) ||
strlen($first_name) <= 3
) {
echo "Your first name is invalid.";
exit();
}
if ( $last_name === "" || !ctype_alnum($last_name) ||
strlen($last_name) < 2
) {
echo "Your last name is invalid.";
exit();
}
// Insert the record into the database
$query = "INSERT into bio_data (first_name, last_name) VALUES ('$first_name', '$last_name')";
$stmt = $connection_string->prepare($query);
$stmt->execute();
if ($stmt->affected_rows === 1) {
echo "Data inserted successfully";
}
} else {
// User manipulated the HTML form or accessed
// the script directly. Kill the script.
echo "An unexpected error occurred. Please, try again later.";
exit();
}
?>
输出(如果处理成功):
Mysqli_real_escape_string
中的错误原因
如果你在 mysqli_real_escape_string
中省略数据库连接,你将收到错误消息。所以,在下面的代码中,我们修改了 process_form.php
。
同时,这个版本没有 mysqli_real_escape_string
中的数据库连接。因此,当你想将数据插入数据库时会出现错误。
<?php
if (isset($_POST['submit_form']) && isset($_POST["first_name"]) && isset($_POST["last_name"])) {
$connection_string = new mysqli("localhost", "root", "", "my_details");
// We've omitted the connection string
$first_name = mysqli_real_escape_string(trim(htmlentities($_POST['first_name'])));
$last_name = mysqli_real_escape_string(trim(htmlentities($_POST['last_name'])));
if ($connection_string->connect_error) {
echo "Failed to connect to Database. Please, check your connection details.";
exit();
}
if ( $first_name === "" || !ctype_alnum($first_name) ||
strlen($first_name) <= 3
) {
echo "Your first name is invalid.";
exit();
}
if ( $last_name === "" || !ctype_alnum($last_name) ||
strlen($last_name) < 2
) {
echo "Your last name is invalid.";
exit();
}
$query = "INSERT into bio_data (first_name, last_name) VALUES ('$first_name', '$last_name')";
$stmt = $connection_string->prepare($query);
$stmt->execute();
if ($stmt->affected_rows === 1) {
echo "Data inserted successfully";
}
} else {
echo "An unexpected error occurred. Please, try again later.";
exit();
}
?>
示例错误消息:
Fatal error: Uncaught ArgumentCountError: mysqli_real_escape_string() expects exactly 2 arguments, 1 given in C:\xampp\htdocs\processformmysqli\process_form.php:12 Stack trace: #0 C:\xampp\htdocs\processformmysqli\process_form.php(12): mysqli_real_escape_string('Johnson') #1 {main} thrown in C:\xampp\htdocs\processformmysqli\process_form.php on line 12
Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.
LinkedIn