dtziv24262 2016-05-29 12:56
浏览 45
已采纳

在PHP登录表单代码中跳过一个IF块

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>
  • 写回答

1条回答 默认 最新

  • douyan6742 2016-05-29 13:34
    关注
    $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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题