Shanojan.A Shanojan.A - 6 months ago 9
SQL Question

One IF block is skipped in PHP login form code

I'm a beginning level PHP programmer. I've created a student login system to display exam marks for my assignment purpose. I have a MySQL DB to store student and marks details. I created two IF blocks to validate empty input fields and wrong credentials. first one is working fine but, another one is not executed. it means, results page is displayed without any details when I enter wrong username and password. Could anyone please help me to find my mistake?

<?php
require '../scripts/database_connection.php';

$username = $_REQUEST['username'];
$password = $_REQUEST['password'];

if (($username != "") && ($password != "")){
$login_query = "SELECT * FROM student WHERE username= " . "'$username' AND password= " . "'$password'";

} else {
die("<p>Username and password cannot be empty</p>");
}

$result = mysql_query($login_query);

if (!$result){
die("<p>Password and username is not correct" . mysql_error() . "</p>");

} else {
$studentrow = mysql_fetch_array($result);
$index = $studentrow['index_no'];
}

?>

<html>
<head>
<title>Results form</title>
<link href="passpaper2014.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Final Results</h2>
<div id="tableContainer">
<p>Name: <?php echo $studentrow['name'];?></p>
<p>Index No: <?php echo $studentrow['index_no']; ?></p>
<table class="table" border="1">
<col width="250">
<col width="80">
<tr>
<th>Subject</th>
<th>Marks</th>
</tr>
<?php
$retrive_query = "SELECT subject,marks FROM mark WHERE index_no= " . "'$index'";
$marksresult = mysql_query($retrive_query);
while ($row = mysql_fetch_array($marksresult)){

echo "
<tr>
<td>". $row['subject'] . "</td>
<td>" . $row['marks'] . "</td>
</tr>";
}

?>
</table>
</div>
</body>
</html>

Answer
$result = mysql_query($login_query);
if (!$result){
    die("<p>Password and username is not correct" . mysql_error() . "</p>");
}

Here is the problem. Even if your query doesn't return any value, $result will contain a query resource, so your if (!$result) is invalid.

This should work:

$result = mysql_query($login_query);
$studentrow = mysql_fetch_array($result);
if (!$studentrow){
    die("<p>Password and username is not correct" . mysql_error() . "</p>");
} else {
    $index = $studentrow['index_no'];
}

As stated in the comments, your code is really vulnerable to SQL injection. Check it and fix before going online with a vulnerable website

This question can help you: How can I prevent SQL-injection in PHP?