******* When we want to write to the database in the PHP project, sometimes the code does not prevent SQL injection, which causes various unpredictable errors.
1. index.htm This is a very simple registration page. I submit data in the form of ajax
Copy the code code as follows:
<! DOCTYPE html PUBLIC "-/ W3C // DTD XHTML 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "Content-Type" content = "text / html; charset = utf-8" />
<title> RegisterForm </ title>
<script type = "text / javascript" src = 'jquery-1.3.1.js'> </ script>
</ head>
<body>
<h1> This is a test form! </ h1>
<font color = "# 8b0000"> <table class = 'tb' border = "0" cellpadding = "5" cellspacing = 0>
<form action = '_ process.php' method = 'post' enctype = 'multipart / form-data'>
<tr> <td class = "tdleft"> <em> user: </ em> </ td> <td> <input type = 'text' id = 'name' name = 'name' value = '' size = 15 /> </ td> </ tr>
<tr> <td class = "tdleft"> <em> ages: </ em> </ td> <td> <input type = 'text' id = 'ages' name = 'ages' value = '' size = 15 /> </ td> </ tr>
<tr> <td class = "tdleft"> <em> pass: </ em> </ td> <td> <input type = 'password' id = 'password' name = 'password' value = '' size = 15 /> </ td> </ tr>
<tr> <td class = "tdleft"> <em> addr: </ em> </ td> <td> <input type = 'text' id = 'addr' name = 'addr' value = '' size = 15 /> </ td> </ tr>
<tr> <td class = "tdleft"> <em> email: </ em> </ td> <td> <input type = 'text' name = 'email' id = 'email' value = '' size = 15 /> </ td> </ tr>
<tr> <td class = "tdleft"> <input type = 'button' value = 'register' id = "but" /> </ td> <td> <input type = 'reset' value = 'reseting' / > </ td> </ tr>
</ form>
</ table> </ font>
<span id = 'msg' style = 'display: none'> Loading ... ... </ span>
<p id = "result" class = ""> </ p>
<style type = "text / css">
body {text-align: center;}
.error {color: red;}
.tb {margin: 0 auto; width: 350px; height: 200px; text-align: center;}
.tdleft {width: 150px; text-align: left;}
</ style>
<script type = 'text / javascript'>
$ ("# but"). click (function () {
var name = $ .trim ($ ("# name"). val ());
var ages = $ .trim ($ ("# ages"). val ());
var pn = / ^ \ d + $ /;
var addr = $ .trim ($ ("# addr"). val ());
var pass = $ .trim ($ ("# password"). val ());
var email = $ .trim ($ ("# email"). val ());
var reg = /^[a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\.[a-zA-Z]+)+$/gi;
if (name.length == 0) {
alert ("Please fill in your name carefully!"); return false;
}
if (ages.length == 0) {
alert ("Please fill in the age!"); return false;
}
if (! pn.test (ages)) {
alert ("Please fill in a valid number!"); return false;
}
if (pass.length == 0 || pass.length> 6) {
alert ("Please fill in the password carefully!"); return false;
}
if (addr.length == 0) {
alert ("Please fill in the address carefully!"); return false;
}
if (email.length == 0) {
alert ("Please fill in the mail carefully!"); return false;
}
if (! reg.test (email)) {
alert ("Email detection failed"); return false;
}
var send = ('name': name, 'ages': ages, 'pass': pass, 'addr': addr, 'email': email};
$ .post ('_ process.php', send, function (data) {
if (data.res ==-1) {
$ ("# result"). addClass ("error");
}
$ ("# result"). html (data.msg);
// $ ("form") [0] .reset ();
}, 'json');
})
$ ("# msg"). ajaxStart (function () {
$ (this) .fadeIn ();
}). ajaxStop (function () {
$ (this) .fadeOut ();
})
</ script>
</ body>
</ html>
2, _process.php receives ajax submission data and does related processing files
Copy the code code as follows:
<? php
header ('Content-Type: text / html; charset = utf-8');
sleep (1);
$ conn = mysqli_connect ("localhost", "root", "root", "register") or die ("Unable to connect!". mysqli_connect_error ());
mysqli_query ($ link, "set names utf8");
$ name = isset ($ _ POST ['name'])? mysqlQuotes (trim ($ _ POST ['name'])): '';
$ ages = isset ($ _ POST ['ages'])? intval (trim ($ _ POST ['ages'])): '';
$ pass = isset ($ _ POST ['pass'])? mysqlQuotes (trim ($ _ POST ['pass'])): '';
$ addr = isset ($ _ POST ['addr'])? mysqlQuotes (trim ($ _ POST ['addr'])): '';
$ email = isset ($ _ POST ['email'])? mysqlQuotes (trim ($ _ POST ['email'])): '';
if (empty ($ name)) {
echo json_encode (array ('res' =>-1, 'msg' => 'Please enter your name carefully')); exit;
}
// Query whether the username exists in the tb_register table. If it does not exist, it will be stored in the database. If it exists, it will be registered.
$ sql0 = "select count (1) as nums from tb_register where username = '{$ name}'";
$ row0 = select_one ($ conn, $ sql0);
if ($ row0 ['nums']> = 1) {
echo json_encode (array ('res' =>-1, 'msg' => 'Sorry, this username is already registered!')); exit;
}
if (empty ($ ages)) {
echo json_encode (array ('res' =>-1, 'msg' => 'Please enter your age carefully')); exit;
}
if (! preg_match ("/ ^ \ d + $ /", $ ages)) {
echo json_encode (array ('res' =>-1, 'msg' => 'Please enter a valid number')); exit;
}
if (empty ($ pass)) {
echo json_encode (array ('res' =>-1, 'msg' => 'Please enter your password carefully')); exit;
}
if (empty ($ addr)) {
echo json_encode (array ('res' =>-1, 'msg' => 'Please enter the address carefully')); exit;
}
if (empty ($ email)) {
echo json_encode (array ('res' =>-1, 'msg' => 'Please enter your mailbox carefully')); exit;
}
if (! preg_match ("/ ^ [a-zA-Z0-9 _] + @ [a-zA-Z0-9 _] + (\. [a-zA-Z] +) + $ /", $ email)) {
echo json_encode (array ('res' =>-1, 'msg' => 'Your mailbox is malformed')); exit;
}
$ add_day = date ("YmdHis");
// The following is the warehouse operation
$ sql = "insert into tb_register set username = '($ name}', ages = '{$ ages}', password = '{$ pass}', address = '($ addr}', email = '{$ email } ', add_day =' {$ add_day} '";
mysqli_query ($ conn, $ sql);
echo json_encode (array ('res' => 1, 'msg' => 'Congratulations, registration is successful!')); exit;
// Prevent MySQL injection attack function
function mysqlQuotes ($ content) {
if (! get_magic_quotes_gpc ()) // Check to see if the automatic filtering mechanism is enabled
{
$ content = addslashes ($ content);
}
return stripslashes (htmlspecialchars ($ content));
}
function select_one ($ conn, $ sql) {
$ res = mysqli_query ($ conn, $ sql) or die ("Failed" .mysqli_error ());
$ result = array ();
if (! empty ($ res)) {
$ result = mysqli_fetch_assoc ($ res);
}
mysqli_free_result ($ res);
return $ result;
}
****** Above custom function mysqlQuotes **********
Tips1, (PS: good PHP Q buckle: 276167802, verification: csl)
addslashes The function of the dslashes function is to add a backslash to the specified characters.
Single quote ('), double quote ("), backslash (\), NULL
Tips2,
The function of the htmlspecialchars function is to convert some special characters into html entities. These specific characters are:
& (And sign) ==> &
"(Double quotes) ==>"
'(Single quote) ==>'
<(Less than sign) ==> <
> (Greater than) ==>>
Tips3,
The stripslashes function deletes the rice slashes added by the addslashes () function, and restores the original appearance.
For example, the $ username user enters Tom’siy
Stored in the database is Tom \ ’siy with a backslash;
Take it out and use stripslashes () to restore it to output Tom’siy
The above is the overall operation flow of this article about submitting form data to the database by Ajax. I hope this article is helpful to the majority of PHP developers. Thanks for reading this article.