This question already has an answer here:
1. how to work php sql injection and use in site ?
my site login process easily login any person with out username & password.plz describe how to safe login process.
example :
$logindetail = "select * from tablename where username = '".$_REQUEST['username']."' and password = '".$_REQUEST['password']."' ";
$sqlrun = mysql_query($logindetail);
$recordcount = mysql_num_rows($sqlrun);
in this login process how would sql injection be used?
</div>
Change first line to:
$logindetail = "select * from tablename where username = '".mysql_real_escape_string($_REQUEST['username'])."' and password = '".mysql_real_escape_string($_REQUEST['password'])."' ";
It's not clear whether you're asking for someone to explain how to prevent SQL injection, or how someone might use SQL injection to get into your site.
To prevent SQL injection, use parameterised queries. This has already been well explained in this question: How can I prevent SQL injection in PHP?
If someone realised your site was vulnerable to SQL injection, they could log on to your site as any known username, by entering this into the username box
admin' OR 1=1 --
This makes the SQL that is executed on the database server:
"select * from tablename where username = 'admin' OR 1=1 -- and password = '' "
The OR 1=1
will evaluate to true and the --
comments out the rest of the SQL string and prevent the password check.
I'm not going to get into password hashing, as I assume this is a small example.
Use prepared statements and parameterized queries.
Can achieve this by using msqli http://php.net/manual/en/book.mysqli.php
quick tutorial. http://www.phphaven.com/article.php?id=65
example code
<?php
// CONNECT TO THE DATABASE
$DB_NAME = 'DATABASE_NAME';
$DB_HOST = 'DATABASE_HOST';
$DB_USER = 'DATABASE_USER';
$DB_PASS = 'DATABASE_PASSWORD';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
// A QUICK QUERY ON A FAKE USER TABLE
$query = "SELECT * FROM `users` WHERE `status`='bonkers'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
// GOING THROUGH THE DATA
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo stripslashes($row['username']);
}
}
else {
echo 'NO RESULTS';
}
// CLOSE CONNECTION
mysqli_close($mysqli);
?>
use mysqli or PDO preprared statements to execute a query. mysql is deprecated.
Something like this:-
<?php
$con = new mysqli('host','user','pass','db');
if(!$con)
die();
$stmt = $con->prepare("select * from tablename where username = ? and password =?");
$stmt->bind_param('ss',$_REQUEST['username'],$_REQUEST['password']);
$stmt->execute();
$stmt->close();
This can be a more safer way to stop SQL injection. Learn more from Here