Using MySQL_real_escape_string to process form data
This article will teach you how to use mysqli_real_escape_string
to process form data.
First, we will set up a sample database and a table. Then we will create an HTML form that accepts user input.
After that, in PHP, we will explain how to use mysqli_real_escape_string
without causing errors.
Setting up a local server
All the code for this article will be run on a server. Therefore, if you have access to a live server, you can skip this section and proceed to the next one.
If you don't have one, install a local server such as XAMPP from Apache Friends. Once XAMPP is installed, find htdocs
the folder and create one.
This folder will store all the code for this article.
Create database and table
In XAMPP, you can phpMyAdmin
create a database using either or the command line. If you are on the command line, log into MySQL using the following command:
#login to mysql
mysql -u root -p
After logging into MySQL, create a database. In this article, we will refer to the database as my_details
.
CREATE database my_details
After creating the database, create a table using the next SQL code. This table will hold the data for our sample project.
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;
Creating the HTML Form
The HTML form will have two form inputs. The first collects the user's first name, and the second collects the last name.
<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>
Output:
Processing tabular data
During form processing, we use mysqli_real_escape_string
to escape form input. More importantly, the database connection should be mysqli_real_escape_string
the first argument to .
So we used below on first and last name mysqli_real_escape_string
. To use this code, save it as 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();
}
?>
Output (if successful):
Mysqli_real_escape_string
Cause of error in
If you mysqli_real_escape_string
omit the database connection in , you will get an error message. So, in the following code, we modified it process_form.php
.
Also, this version does not have mysqli_real_escape_string
a database connection in . Therefore, you will get an error when you want to insert data into the database.
<?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();
}
?>
Example error message:
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
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Changing max_allowed_packet Size in MySQL Server
Publish Date:2025/04/22 Views:192 Category:MySQL
-
This article explains how to change the max_allowed_packet size in MySQL server. To understand this, we will use two operating systems, Windows 10 and Linux (Ubuntu). Changing max_allowed_packet Size in MySQL Server If we try to upload a fi
Zerofill usage, advantages and alternatives in MySQL
Publish Date:2025/04/22 Views:195 Category:MySQL
-
In this article we will understand the uses, advantages and alternatives of ZEROFILL attribute in MySQL. Use and benefits of the ZEROFILL attribute in MySQL The benefit of using the ZEROFILL attribute is that it has nothing to do with input
Compare only MySQL timestamp dates to date parameters
Publish Date:2025/04/22 Views:64 Category:MySQL
-
In this article we will use the DATE() , CAST() , and CONVERT() functions to compare MySQL timestamp dates with only the date parameter. DATE() vs. CAST() vs. CONVERT() in MySQL Below is a brief description of each function. You can also fi
Calculating Percentages in MySQL
Publish Date:2025/04/22 Views:66 Category:MySQL
-
We will use one or more columns to calculate percentages in MySQL. There are different ways to do this, and for each method we will use an example table. Calculate percentage using a column in MySQL We have a table called sales where ID, Re
Selecting multiple values using WHERE in MySQL
Publish Date:2025/04/22 Views:185 Category:MySQL
-
This article is about using MySQL query to get data from a specific table or relation that satisfies a specific condition. To do this, the WHERE clause is used in the SQL query. WHERE clause in SQL query WHERE The clause specifies the condi
Changing the connection timeout in MySQL
Publish Date:2025/04/22 Views:59 Category:MySQL
-
We are learning how to change the connection timeout in MySQL using Linux (Ubuntu 20.04) and Windows operating systems. Changing the connection timeout in MySQL Sometimes you keep losing connection to the MySQL server because the connect_ti
MySQL fix Data Is Truncated for a Column error
Publish Date:2025/04/22 Views:101 Category:MySQL
-
This article describes possible causes and solutions for the MySQL error Data is truncated for a column . Fix data truncated due to column error in MySQL Here, we will discuss the possible causes and solutions to eliminate MySQL data trunca
MySQL Error Server PID File Could Not Be Found Solution
Publish Date:2025/04/22 Views:192 Category:MySQL
-
In this article, we will study about the Error! Error Server PID File Could Not Be Found! in MySQL and its solution with full explanation. MySQL PID file The file that contains the process identification number or process ID of a running My
Get the last inserted ID using PHP MySQLi function
Publish Date:2025/04/22 Views:99 Category:MySQL
-
This article briefly introduces the PHP mysqli() function and demonstrates how to use it to get the last inserted ID from a MySQL database. PHP mysqli() Function It is an extended version of the MySQL driver called mysqli and is typically u