如何使用准备好的语句创建唯一的用户名和电子邮件?我知道我的代码是错误的,因为到目前为止,如果我输入已经使用的用户名,则将显示正确的错误消息,但是即使电子邮件是唯一的,错误消息也会显示在电子邮件中(反之亦然)。 / p>
关于如何解决此问题的任何想法?
else {
$sql = "SELECT * FROM users WHERE user_name=? OR user_email=?";
$stmt = mysqli_stmt_init($con);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $name, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
array_push($error_array, "taken.<br>");
}
答案 0 :(得分:0)
ALTER TABLE users ADD UNIQUE (user_name);
ALTER TABLE users ADD UNIQUE (user_email);
答案 1 :(得分:0)
像这样尝试。如果您想拥有2种情况,则必须询问两次:)
$stmt->bind_result($db_name, $db_email);
$stmt->fetch();
if($db_name == $name) {
array_push($error_array, "name taken.<br>");
}
if($db_email == $email) {
array_push($error_array, "email taken.<br>");
}
答案 2 :(得分:0)
这里是我的意思的一个例子,如果您只是更改那(2)个数据库列。...
<?php
$_POST['user_name'] = 'admin'; // should be cleaned and validated
$_POST['user_email'] = 'test@gmail.com'; // should be cleaned and validated
/* open a connection */
$con = mysqli_connect ( 'localhost', 'login_user', 'login_pass', 'database' );
/* check the connection */
if ( mysqli_connect_errno ( ) )
{
echo "Connect failed: " . mysqli_connect_error () . "\r\n\r\n";
exit ( );
}
/* initialize the statement */
$stmt = mysqli_stmt_init ( $con );
/* the query / sql statement */
$sql = "INSERT INTO users (user_name, user_email) VALUES (?,?);";
/* test the sql statement */
if ( mysqli_stmt_prepare ( $stmt, $sql ) === TRUE )
{
/* bind the param(s) to the sql statement */
mysqli_stmt_bind_param ( $stmt, "ss", $_POST['user_name'], $_POST['user_email'] );
/* try to execute the sql statement */
if ( mysqli_stmt_execute ( $stmt ) === FALSE )
{
/* show developer error, duplicate found, this would not be here */
echo "Error: " . mysqli_error ( $con ) . "\r\n\r\n";
/* show the user error, duplicate found */
echo "Error: the username and or password already exist on are system\r\n";
exit ( );
}
else
{
/* close the sql statement */
mysqli_stmt_close ( $stmt );
echo "New User Added\r\n\r\n";
exit ( );
}
}
else /* query, sql statement error */
{
echo "Query Error: " . mysqli_error ( $con ) . "\r\n\r\n";
}
/* close the connection */
mysqli_close ( $con );
?>