dongxu3029
dongxu3029
2018-12-04 19:33
浏览 29
已采纳

检查数据库中是否已存在loginName

What I want to achieve: a check to see whether the "name" already exists in one of my rows.

Problem: It keeps on adding rows even though they already exist.

I have been looking around on StackOverflow, but haven't really found something that could possibly be causing the same problem.

Yes, I have checked my type in mysqli_db, it's a VARCHAR (255). So the type I am passing on is a "string" (I am using prepared statements).

I have already checked the variable $loginName, this one is also correct (as in the right variable im passing on).

I have also checked whether I made a typo in my $sqli statement relating to the table or row (loginName), but the sqli statement is correct.

How my code looks like:

include_once 'dbConn.php';
 $loginName = $_POST['loginName'];
 $userName = $_POST['userName'];
 $pwd = $_POST['pwd'];
 $confirmPWD = $_POST['confirmPWD'];

            $sqli = "SELECT * FROM registerandlogin WHERE loginName = ?";
            $stmt = mysqli_stmt_init($conn);

            if (!mysqli_stmt_prepare($stmt, $sqli)) {
                header('Location: index.php?prep=failed');
                exit();
            } else {
                mysqli_stmt_bind_param($stmt, 's', $loginName);
                $result = mysqli_stmt_get_result($stmt);
                $resultCheck = mysqli_num_rows($result);

                if ($resultCheck > 0) {
                    header('Location: index.php?loginName=taken');
                    exit();
                } else {
//do something else  
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxuanjie2692
    douxuanjie2692 2018-12-05 14:18
    已采纳

    I forgot the following piece of code: mysqli_stmt_execute($stmt);.

    Therefore the if statement never fired.

    Wrong:

                mysqli_stmt_bind_param($stmt, 's', $loginName);
                $result = mysqli_stmt_get_result($stmt);
                $resultCheck = mysqli_num_rows($result);
    

    Right:

                mysqli_stmt_bind_param($stmt, 's', $loginName);
                mysqli_stmt_execute($stmt);
                $result = mysqli_stmt_get_result($stmt);
                $resultCheck = mysqli_num_rows($result);
    
    点赞 评论

相关推荐