Share the complete Ajax operation process for submitting form data to warehouse receiving

Source: Internet
Author: User
Tags mysql injection

* ****** When writing data to the database in the php project, sometimes the Code does not prevent SQL injection, cause various unpredictable errors *******

1. index.htm this is a very simple registration page l I submit data in ajax form
Copy codeThe Code is 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> <input type = 'text' id = 'name' name = 'name' value = ''size = 15/> </td> </tr>
<Tr> <td class = "tdleft"> <em> ages: </em> </td> <input type = 'text' id = 'AGES 'name = 'AGES 'value = ''size = 15/> </td> </tr>
<Tr> <td class = "tdleft"> <em> pass: </em> </td> <input type = 'Password' id = 'Password' name = 'Password' value = ''size = 15/> </td> </tr>
<Tr> <td class = "tdleft"> <em> addr: </em> </td> <input type = 'text' id = 'addr 'name = 'addr 'value = ''size = 15/> </td> </tr>
<Tr> <td class = "tdleft"> <em> email: </em> </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> <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 enter your name carefully! "); Return false;
}
If (ages. length = 0 ){
Alert ("Enter age! "); Return false;
}
If (! Pn. test (ages )){
Alert ("enter a valid number! "); Return false;
}
If (pass. length = 0 | pass. length> 6 ){
Alert ("enter the password carefully! "); Return false;
}
If (addr. length = 0 ){
Alert ("Please enter the address carefully! "); Return false;
}
If (email. length = 0 ){
Alert ("please fill in the email 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" pai.html (data. msg );
// $ ("Form") [0]. reset ();
}, 'Json ');
})
$ ("# Msg"). ajaxStart (function (){
$ (This). fadeIn ();
}). AjaxStop (function (){
$ (This). fadeOut ();
})
</Script>
</Body>
</Html>

2, _ process. php receives files submitted by ajax and processed accordingly
Copy codeThe Code is 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' => 'enter your name' carefully); exit;
}
// Query whether the username exists in the tb_register table. If the username does not exist, the database enters the database. If the username exists, the registered username is notified.
$ 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 user name has been registered! '); Exit;
}
If (empty ($ ages )){
Echo json_encode (array ('res '=>-1, 'msg' => 'enter your age' carefully); exit;
}
If (! Preg_match ("/^ \ d + $/", $ ages )){
Echo json_encode (array ('res '=>-1, 'msg' => 'enter a valid number'); exit;
}
If (empty ($ pass )){
Echo json_encode (array ('res '=>-1, 'msg' => 'enter your password' carefully); exit;
}
If (empty ($ addr )){
Echo json_encode (array ('res '=>-1, 'msg' => 'enter the address carefully'); exit;
}
If (empty ($ email )){
Echo json_encode (array ('res '=>-1, 'msg' => 'Please input the 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 format is incorrect '); exit;
}
$ Add_day = date ("YmdHis ");

// The following is the warehouse receiving 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 successful! '); Exit;


// Prevents mysql injection attacks. function data is stored in the database.
Function mysqlQuotes ($ content ){
If (! Get_magic_quotes_gpc () // first, check whether the automatic filtering function is enabled. If the function is not enabled, add a function to filter data.
{
$ 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;
}

* ****** ********** In the preceding custom function mysqlQuotes **********
Tips1, (PS: T good php q buckle: 276167802, verification: csl)
The addslashes function is used to add a backslash to a specified character, mainly including the following special characters
Single quotes ('), double quotes ("), backslash (\), NULL


Tips2,
The htmlspecialchars function is used to convert some special characters into html entities. These specific characters include:
& (And number) ==> &
"(Double quotation marks) =>"
'(Single quotes) =>'
<(Minor sign) => <
> (Greater than the number) ==>>

Tips3,
The stripslashes function is used to delete the slash added by the addslashes () function and restore the original touch.
For example, the $ username user inputs Tom 'siy.
The Tom \ 'siy with the backslash added to the database;

You can use stripslashes () to restore it and output Tom 'siy.

The above is the complete operation process for submitting form data to the database via Ajax. I hope this article will be helpful to the majority of php developers. Thank you for reading this article.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.