我在网站上有一个表单,需要在将表单数据输入数据库之前进行验证。
它通过用户 mysql_num_rows 函数检查用户名是否已经存在。但我似乎无法让它工作。测试时,它不允许添加新用户名。
这是正在使用的完整代码:
<?php
session_start();
include("databaseConnect.php");
// Insert a row of information into the table "example"
// check if username is already in database
if(mysql_num_rows(mysql_query("SELECT userName FROM registeredUsers WHERE userName = '$_POST[userName]'"))){
echo "Username: ". $_POST[userName]." already exists in the Database<br><br>";
echo "You will be redirect back to the form in 5 seconds";
$ref = $_SERVER['HTTP_REFERER'];
header( 'refresh: 5; url='.$ref);
//check if hemis is already in database
}elseif(mysql_num_rows(mysql_query("SELECT hemis FROM registeredUsers WHERE hemis = '$_POST[hemis]'"))){
echo "Student [Hemis] Number: ". $_POST[hemis]." already exists in the Database<br><br>";
echo "You will be redirect back to the form in 5 seconds";
$ref = $_SERVER['HTTP_REFERER'];
header( 'refresh: 5; url='.$ref);
// if all the conditions above are fine, it will insert the data to MySQL
}else{
mysql_query("INSERT INTO registeredUsers
(firstName, lastName, hemis, userName, MAC) VALUES('$_POST[firstName]', '$_POST[lastName]', '$_POST[hemis]', '$_POST[userName]', '$_POST[mac]' ) ")
or die(mysql_error());
echo "Data Inserted! <br><br>";
}
非常感谢 :)