我目前正在为我的网站构建一个注册脚本。我是整个PHP-mySQL交互位的新手。无论如何,这是我到目前为止所获得的代码。问题是我添加了一些代码来检查用户名是否已经存在于数据库中,在表单提交后将其踢到store.viddir.com/join/signup.php而不是store.viddir.com/login,就像我有它。任何可以帮助新手的专业人士?非常感谢
<?php
$submitted = $_POST["submitted"];
if($submitted == 'yes') {
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$userName = $_POST["userName"];
$password = $_POST["password"];
$confirmPassword = $_POST["confirmPassword"];
$eMail = $_POST["eMail"];
// Kill script if input fields are blank
if ($firstName == '' or $lastName == '' or $userName == '' or $password == '' or $confirmPassword == '' or $eMail == '')
{
die();
}
// Check if passwords match
if ($password != $confirmPassword)
{
die();
}
// Check if password is appropriat length
$passwordLength = strlen($password);
if ($passwordLength < 7 or $passwordLength >30) {
die();
}
/////////////////////////
// Connect to database //
/////////////////////////
$sqlserver = "localhost";
$sqluser = "XXXX";
$sqlpassword = "XXXXXX";
mysql_connect($sqlserver, $sqluser, $sqlpassword) or die(mysql_error());
mysql_select_db("store");
// Check database if username already exists
$newUserName = $userName;
$checkUserName = mysql_query("SELECT userName FROM userInfo WHERE userName = '$newUserName'");
if ($checkUserName) {
die();
}
//////////////////////////
// Insert into database //
//////////////////////////
// Signup time in Unix Epoch
$time = time();
// Human readable date
$date = date("F jS, Y g:i:s A");
$sql = "INSERT into userInfo (firstName, lastName, userName, password, eMail, time, date) VALUES ('$firstName', '$lastName', '$userName', '$password', '$eMail', '$time', '$date')";
//$sqlserver = "localhost";
//$sqluser = "XXXX";
//$sqlpassword = "XXXXXX";
//mysql_connect($sqlserver, $sqluser, $sqlpassword) or die(mysql_error());
//mysql_select_db("store");
mysql_query($sql) or die(mysql_error());
mysql_close();
header("Location: http://store.viddir.com/login");
exit;
}
?>
答案 0 :(得分:0)
请参阅mysql_num_rows。您还应该考虑使用PDO或MySQLi
http://php.net/manual/en/function.mysql-num-rows.php
if (mysql_num_rows($query) > 0) {
echo "user already exists";
}
答案 1 :(得分:0)
您应该在mysql查询中进行计数,然后检查结果是否不等于0.
示例:
// Check database if username already exists
$newUserName = $userName;
$checkUserName = mysql_query("SELECT COUNT(userName) FROM userInfo WHERE userName = '$newUserName'");
if ( mysql_result($checkUserName, 0, 0) != 0 ) {
die();
}