tags:

views:

67

answers:

3

Hello,

*EDIT*Thanks to the comments below it has been figured out that the problem lies with the md5, without everything works as it should.
But how do i implent the md5 then?

I am having some troubles with the following code below to login.
The database and register system are already working.
The problem lies that it does not find any result at all in the query.
IF the count is > 0 it should redirect the user to a secured page.
But this only works if i write count >= 0, but this should be > 0 , only if the user name and password is found he should be directed to the secure (startpage) of the site after login.
For example root (username) root (password) already exists but i cannot seem to properly login with it.

<?php
session_start();

if (!empty($_POST["send"]))
{   
$username = ($_POST["username"]);
$password = (md5($_POST["password"])); 
$count = 0;

$con = mysql_connect("localhost" , "root", "");

mysql_select_db("testdb", $con);

$result = mysql_query("SELECT name, password FROM user WHERE name = '".$username."' AND password = '".$password."' ")
    or die("Error select statement");


$count = mysql_num_rows($result);


if($count > 0) // always goes the to else, only works with >=0 but then the data is not found in the database, hence incorrect
{
    $row = mysql_fetch_array($result);

    $_SESSION["username"] = $row["name"];
    header("Location: StartPage.php");
}
else
{
    echo "Wrong login data, please try again";
}

mysql_close($con);    
}

?>
+2  A: 

The best thing you can do in such situations is trying to find out where the problem lies. So, you could proceed by steps and do the following:

1) start your script with a print_r($_POST), to see what variables are passed by post (by absurd, the problem might even be related to the 'send' guard parameter you have ..IE a form being sent through get)

2) Assign your query to a variable (...and don't forget to escape parameters!) and print it to screen; and then exec it on mysql (or phpmyadmin) to see what results they give.

As a side note, as someone already pointed out, this code might be subject to SQL-injection, so you might consider using prepared statements; see here: quick intro

maraspin
A: 

Your login code is good.

But you also need to use md5() function BEFORE storing the password in the database. So when you are inserting the user record in the DB , apply the md5() to the password , save in the DB. Now when you will try to find the record on login, it will match correctly.

Sabeen Malik
A: 

You should rewrite this with mysqli or PDO and using a newer hash function as well as a salt. MD5 is very widely used and is a target for crackers.

Xanti SS