如何用PHP验证MySQL中的多个表单字段?

时间:2014-06-08 18:52:49

标签: php mysql forms validation field

我正在尝试构建一个登录表单,用户必须在表单中添加此数据:名字,姓氏,学生编号和电子邮件。

我的MySQL数据库中有一个测试用户,但到目前为止它还没有用。这是我的代码:

<?php
//Start session//
session_start();

//Include database connection file and header file//
include_once('resources/includes/database.inc.php');
include_once('header.php');

?>

<!-- Login form -->

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//Escape de gebruikersnaam
$sFirstName = mysql_real_escape_string($_POST['firstname']);
$sLastName = mysql_real_escape_string($_POST['lastname']);
$sStudentNumber = ($_POST['studentnumber']);
$sEmail = ($_POST['email']);
$sSQL = 'SELECT `id`, `firstName`, `lastName`, `studentNumber`, `email`, `accepted` FROM   `student` WHERE `firstName` = \'' . $sFirstName . '\'';
$rsSQL = mysql_query($sSQL);
$aUser = mysql_fetch_array($rsSQL);
  //Er is geen rij gevonden en $aUser is false:
//Dat betekent dat er geen user is met de opgegeven gebruikersnaam
if($aUser == false)
{
    echo '<strong>Deze gebruiker is niet gevonden</strong>';
}
//Vergelijk de rest
elseif($aUser['lastname'] != $sLastName)
{
  echo '<strong>De achternaam is niet bekend</strong>';
}

elseif($aUser['studentnumber'] != $sStudentNumber)
{
    echo '<strong>Het studentnummer is niet geldig</strong>';
}

elseif($aUser['email'] != $sEmail)
{
  echo '<strong>Het e-mailadres is niet bekend</strong>';
}

//Inloggen gelukt
else
{        //De combinatie is goed, maak de sessie aan
    $_SESSION['login_user'] = $aUser['id'];

    //Verstuur de gebruiker door
    header("location: studentloggedin.php");

    //Mocht de redirect hierboven niet werken:
    echo '<strong>Je bent ingelogd, klik <a href="studentloggedin.php">hier</a> om door te gaan.</strong>';
}
}
?>

<form method="post">
<table>
<tr>
  <td>Voornaam</td>
  <td><input type="text" name="firstname" /></td>
</tr>

<tr>
  <td>Achternaam</td>
  <td><input type="text" name="lastname" /></td>
</tr>

<tr>
  <td>Studentnummer</td>
  <td><input type="text" name="studentnumber" /></td>
</tr>

<tr>
  <td>Email</td>
  <td><input type="text" name="email" /></td>
</tr>

<tr>
  <td><input type="submit" value="Inloggen" /></td>
</tr>

</table>
</form>
<?php
$html = file_get_contents('resources/templates/homecontent.template.html');
print $html;
include_once('resources/templates/footer.template.html');
?>

任何人都知道我做错了什么?如果我根据我的数据库用户正确填写所有内容,我会得到:'de achternaam is niet bekend'(姓氏无法识别)。也许我应该检查MySQL查询中的验证?

1 个答案:

答案 0 :(得分:1)

数组键区分大小写。

$aUser['lastname']!= $aUser['lastName']

由于不推荐使用MySQL API,您也应该离开mysql_。将PDO或MySQLi与预准备语句一起使用以避免SQL注入。现在,您的查询可以直接在查询中使用$_POST变量进行注入。

出于调试目的,如果您将来遇到问题,我建议您打印出阵列:print_r($aUser)。它可能为你带来了一次旅行。