PHP Security Pt 5 SQL Injection

SQL InjectionA few months ago a friend asked me to take a look at their website because they had been receiving an immense amount of spam. Worse yet they were also receiving threats from others to stop sending spam to them. I immediately knew they were being targeted by code injection, but as I dug around I found more danger than I was expecting.

It seems that their grandchild (No doubt a future Mark Zuckerberg) had created the shopping cart for them. The shopping cart application had little to know security. In seconds I was able to dump all of their customers credit card information on to the screen before their frightened eyes.

In this video tutorial I’ll show you all of the mistakes that were made along with some other tips that will help you defend your site from SQL Injection.

NOTE: If you think websites are almost never susceptible to SQL Injection, I personally have seen flaws in 1/4th of the sites I have looked at! Industry analysts believe the percentage is closer to 1/3rd!

Like always the code used in the tutorial follows the video. You can use it however you like, but I’m not guaranteeing it is 100% secure, just that it is more secure than most code you will find. Leave questions or comments below.

Code From The Video


<?php      require_once(“./includes/configbad.php”);?>      <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
<html xmlns=”” lang=”en” xml:lang=”en”>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″ />
<title>Good Login</title>
<div id=”main”>
if (isset($_POST[‘submitted’])) {

if (preg_match (‘%^[A-Za-z0-9]\S{8,20}$%’, stripslashes(trim($_POST[‘userid’])))) {
$u = escape_data($_POST[‘userid’]);
} else {
$u = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid User ID!</font></p>’;
if (preg_match (‘%^[A-Za-z0-9]\S{8,20}$%’, stripslashes(trim($_POST[‘pass’])))) {
$p = escape_data($_POST[‘pass’]);
} else {
$p = FALSE;
echo ‘<p><font color=”red” size=”+1″>Please enter a valid Password!</font></p>’;
$captchchk = 1;


$privatekey = “privatekey”;

$resp = recaptcha_check_answer ($privatekey,




if (!$resp->is_valid) {

echo ‘<p><font color=”red” size=”+1″>The CAPTCHA Code wasn\’t entered correctly!</font></p>’;

$captchchk = 0;


if ($u && $p && $captchchk) {
$query = “SELECT user_id, first_name, last_name, email, userid, pass FROM users WHERE userid=’$u’ AND pass=SHA(‘$p’)”;

$result = mysql_query ($query) or trigger_error(“Either the Userid or Password are incorrect”);

if (mysql_affected_rows() == 1) {
// Register the values & redirect. I didn’t write this part
$row = mysql_fetch_array ($result, MYSQL_NUM);

echo “First name: ” . $row[1] . “<br />”;

echo “Last name: ” . $row[2] . “<br />”;

echo “Email: ” . $row[3] . “<br />”;

echo “Login Id: ” . $row[4] . “<br />”;

echo “Password: ” . $row[5] . “<br />”;

while ($row = mysql_fetch_assoc($result))


echo “First name: ” . $row[‘first_name’] . “<br />”;

echo “Last name: ” . $row[‘last_name’] . “<br />”;

echo “Email: ” . $row[’email’] . “<br />”;

echo “Login Id: ” . $row[‘userid’] . “<br />”;

echo “Password: ” . $row[‘pass’] . “<br />”;

} mysql_close();

} else { // No match was made.
echo ‘<br><br><p><font color=”red” size=”+1″>Either the Userid or Password are incorrect</font></p>’;


exit(); }
} echo ‘<br><br><p><font color=”red” size=”+1″>Either the Userid or Password are incorrect</font></p>’;


}// End of SUBMIT conditional.
<p>Your browser must allow cookies in order to log in.</p>
<form action=”goodlogin.php” method=”post”>

<p><b>Userid:</b> <input type=”text” name=”userid” size=”20″ maxlength=”20″ /></p>
<p><b>Password:</b> <input type=”password” name=”pass” size=”20″ maxlength=”20″ /></p>

<?php          require_once(‘recaptchalib.php’);

$publickey = “publickey”; // you got this from the signup page

echo recaptcha_get_html($publickey);

<div align=”center”><input type=”submit” name=”submit” value=”Login” /></div>
<input type=”hidden” name=”submitted” value=”TRUE” />


This code isn’t bad. It will actually clean most security issues

// Define these as constants so that they can’t be changed
DEFINE (‘DBUSER’, ‘mysqladm’);
DEFINE (‘DBPW’, ‘password’);
DEFINE (‘DBHOST’, ‘localhost’);
DEFINE (‘DBNAME’, ‘hamdb’);
if ($dbc = mysql_connect (DBHOST, DBUSER, DBPW)) {
if (!mysql_select_db (DBNAME)) { // If it can’t select the database.
// Handle the error.
trigger_error(“Could not select the database!<br />MySQL Error: ” . mysql_error());
} // End of mysql_select_db IF.
} else {
// Print a message to the user, and kill the script.
trigger_error(“Could not connect to MySQL!<br />MySQL Error: ” . mysql_error());
// A function that strips harmful data.
function escape_data ($data) {
// Check for mysql_real_escape_string() support.
// This function escapes characters that could be used for sql injection
if (function_exists(‘mysql_real_escape_string’)) {
global $dbc; // Need the connection.
$data = mysql_real_escape_string (trim($data), $dbc);
$data = strip_tags($data);
} else {
$data = mysql_escape_string (trim($data));
$data = strip_tags($data);
// Return the escaped value.
return $data;

7 Responses to “PHP Security Pt 5 SQL Injection”

  1. Luis says:

    Please what is the code of the function “escape_data()”.

  2. Anonymous says:

    In your note, you say the ‘percentage’ is closer to 1/3…. you mean the ‘fraction’ is closer to 1/3. Other than that, love all your tutorials!

  3. Anonymous says:

    In second paragraph, you say ‘little to know security.” It should be “little to NO security.”

    • admin says:

      Sorry that typo slipped in. I crank out videos / code very fast and sometimes I have typos here and there. I tend to focus on the code working more than anything else.

  4. Luka says:

    I am a total newb, all my knowledge of php comes from your tutorials.
    I used this files for my website but dreamwaver reports errors on the functions require_once and trigger_error.
    As if thy were never difined.
    Tnx for info

Leave a Reply

Your email address will not be published.