1The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection.
2
3Object oriented style:
4$mysqli -> real_escape_string(escapestring)
5
6$mysqli = new mysqli("localhost","my_user","my_password","my_db");
7
8// Escape special characters, if any
9$firstname = $mysqli -> real_escape_string($_POST['firstname']);
10$lastname = $mysqli -> real_escape_string($_POST['lastname']);
11$age = $mysqli -> real_escape_string($_POST['age']);
12
13Procedural style:
14mysqli_real_escape_string(connection, escapestring)
15
16$con = mysqli_connect("localhost","my_user","my_password","my_db");
17
18// Escape special characters, if any
19$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
20$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
21$age = mysqli_real_escape_string($con, $_POST['age']);
1
2<?php
3
4mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
5$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
6
7$city = "'s-Hertogenbosch";
8
9/* this query with escaped $city will work */
10$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'",
11 mysqli_real_escape_string($mysqli, $city));
12$resu = mysqli_query($mysqli, $query);
13printf("Select returned %d rows.\n", mysqli_num_rows($result));
14
15/* this query will fail, because we didn't escape $city */
16$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
17$result = mysqli_query($mysqli, $query);
18
19
1jQuery(document).ready(function($){
2
3 // hide messages
4 $("#error").hide();
5 $("#sent-form-msg").hide();
6
7 // on submit...
8 $("#contactForm #submit").click(function() {
9 $("#error").hide();
10
11 //required:
12
13 //name
14 var name = $("input#name").val();
15 if(name == ""){
16 $("#error").fadeIn().text("Name required.");
17 $("input#name").focus();
18 return false;
19 }
20
21 // email
22 var email = $("input#email").val();
23 if(email == ""){
24 $("#error").fadeIn().text("Email required");
25 $("input#email").focus();
26 return false;
27 }
28
29 // contact_no
30 var contact_no = $("input#contact_no").val();
31 if(contact_no == ""){
32 $("#error").fadeIn().text("Contact number required");
33 $("input#contact_no").focus();
34 return false;
35 }
36
37 // comments
38 var comments = $("#comments").val();
39
40
41 // data string
42 var dataString = 'name='+ name
43 + '&email=' + email
44 + '&contact_no=' + contact_no
45 + '&comments=' + comments
46
47 // ajax
48 $.ajax({
49 type:"POST",
50 data: dataString,
51 success: success()
52 });
53 });
54
55
56 // on success...
57 function success(){
58 $("#sent-form-msg").fadeIn();
59 $("#contactForm").fadeOut();
60 }
61
62 return false;
63});
64