juan santiago velasco juan santiago velasco - 4 months ago 21
PHP Question

PHP database syntax error

Hi I am new to php programming and tried to create a encrypted password but the problem is it always generate the same md5 for different passwords and I can't log in using the login.php Here is my code

<?php

$name = $_POST['name'];
$password = md5($_POST['password']);

if($name && $password){

mysql_connect("localhost","root","") or die(mysql_error);
mysql_select_db("myfirstdatabase") or die(mysql_error);

$query = mysql_query("SELECT * FROM usernames WHERE name='$name'");
$numrows = mysql_num_rows($query);

if ($numrows != 0){

while ($row = mysql_fetch_assoc($query)){
$dbname = $row['name'];
$dbpassword = $row['password'];

}
if ($name==$dbname){
if($password==$dbpassword){

header("location: users.php");

}else {
echo "Your password is incorrect!";
}
}else{

echo "Your name is incorrect!";
}





}else {
echo "Name is not registered!";
}

}else{

echo "You have to type a name and password";
}

?>

Answer

You have to do it like below:-

<?php
error_reporting(E_ALL); // check all errors
ini_set('display_errors',1);// show all errors
if(isset($_POST['name']) && isset($_POST['password'])){
    $conn = mysqli_connect("localhost","root","","myfirstdatabase");
    if($conn){
        $name = mysqli_real_escape_string($conn,$_POST['name']);
        $password = mysqli_real_escape_string($conn,md5($_POST['password']));
        $query = mysqli_query($conn,"SELECT * FROM usernames WHERE name= $name AND password = $password");
        if(mysqli_num_row($query)>0){           
            header("location: users.php");   
        }else {
            echo "user name or password is incorrect!";
        }
    }else{
        echo "deb connection error:-".mysqli_connect_error();
    }
}else{
   echo "Please fill form fully";
}
?>

Suggestions:-

1.Don't use mysql_*(deprecated from php5.5 onward and removed from php7). Use mysqli_* OR PDO

2.Use password hasing mechanism instead of md5.

3.Use prepared statements of mysqli or PDO to prevent your code from SQL Injection.