0

I've been told that this code is old way of connecting and is susceptible to sql injections. How can I make it secure?

This is the code I use to check a database for users and add a new user if they don't have an account. I tried mysqli but I don't think I got it right so I had to go back to this for now until I know how to make it secure.

<?php
// Connect to the database(host, username, password)
$con = mysql_connect('localhost','user1','pass1');
if (!$con)
{
    echo "Failed to make connection.";
    exit;
}
// Select the database. Enter the name of your database (not the same as the table name)
$db = mysql_select_db('db1');
if (!$db)
{
    echo "Failed to select db.";
    exit;
}
// $_POST['username'] and $_POST['password'] are the param names we sent in our click event in login.js
$username = $_POST['username'];
$password = $_POST['password'];
// Select eveything from the users table where username field == the username we posted and password field == the password we posted
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
    $row = mysql_fetch_array($query);
    $response = array(
        'logged' => true,
        'name' => $row['name'],
        'email' => $row['email']
    );
    echo json_encode($response);
}
else
{
    // Else the username and/or password was invalid! Create an array, json_encode it and echo it out
    $response = array(
        'logged' => false,
        'message' => 'Invalid Username and/or Password'
    );
    echo json_encode($response);
}
?>
3
  • php.net/manual/en/book.pdo.php - billions of examples on SO. Commented Sep 29, 2012 at 0:59
  • PDO, MySQLi or, at a minimum sanitize your inputs Commented Sep 29, 2012 at 1:00
  • Before you learn anything else, try to get accustomed to the Google. Commented Sep 29, 2012 at 1:03

1 Answer 1

1

Any data coming from a user should be passed through mysql_real_escape_string(). See the URL below for more information on using that function. It's very important.

http://php.net/manual/en/function.mysql-real-escape-string.php

Here is a little more information on SQL Injections with PHP:

http://php.net/manual/en/security.database.sql-injection.php

MySQLi Information (another technique besides mysql_real_escape_string):

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

EDIT: OK, I'll admit, I'm kinda old-school. MySQLi definitely seems to be the way to go. I'm more familiar with PHP3 and PHP4 development. If you can, re-implement your data-access code using the last link.

Sign up to request clarification or add additional context in comments.

1 Comment

Seconding prepared statements. Save yourself the worry.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.