-3

I am new to PHP and am not sure if my code will prevent it from any SQL attacks. And also, I was confused as to why I cannot logon. It does not give me any error.

    <?php
$host="localhost"; // Host name
$username="*****"; // Mysql username
$password="****"; // Mysql password
$db_name="***"; // Database name
$tbl_name="electoral"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];

// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$sql="SELECT * FROM $tbl_name WHERE username='$username' and password= md5('$password')";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
// Register $myusername, $mypassword and redirect to file "_____"

session_register("username");
session_register("password");
header("location:electoralcommission.php");
}

?>

any ideas? thanks

Jahed Hussain
  • 111
  • 1
  • 1
  • 7

1 Answers1

1

stripslahes() is unnecessary, and really not a good idea to use. mysql_real_escape_string() is the preferred if you're going to be escaping the string to prevent injections.

Personally, I would recommend you use PDO with Parameterized Queries instead. Parameterized Queries are far, far cleaner than trying to remember if you properly escaped the string or not, plus it at least with some database & driver combinations (not sure about PHP specifically) it will allow the SQL server to cache parts of the query, for better performance (plus, I doubt mysql_... is anything close to speedy!). See this stack overflow page for more information (or many, many other questions).

Community
  • 1
  • 1
Kitsune
  • 8,581
  • 2
  • 23
  • 24