dongqiang1226 2017-01-29 14:01
浏览 13
已采纳

比较使用PHP在MySQL表中是否存在值

Given the following code:

$checkuname = $connect->prepare('SELECT * FROM user WHERE username = ?');
$checkuname->bind_param("s", $uname);

$checkemail = $connect->prepare('SELECT * FROM user WHERE email = ?');
$checkemail->bind_param("s", $email);

$match = 0;

if ($checkuname->execute()) {
    //if username matches//
    $erroruname = "This username exists, please enter a new one";
    $match = $match + 1;
    }
if ($checkemail->execute()) {
    //if email matches//
    $erroremail = "This email has been used, please enter another one";
    $match = $match + 1;
    }
if ($match == 0) { //if no match, good to push data into database// }

No matter what happens, it always returns me saying that username exists (when it doesn't).
Is there any way to correct this?

Or if you think there would be an easier or clearer way to check if both username and email exists in a database, please do share too.

Just to mention too: Most tutorials I have found uses a single variable to check, but I need to check 2 variables

  • 写回答

2条回答 默认 最新

  • dongqiang8474 2017-01-31 23:52
    关注

    "@Fred-ii- I'll invite you to post an answer and I'll mark it as solved – Timothy Wong Glash"

    As requested by the OP:

    You can do this in one query.

    $query = "SELECT `email`, `username` FROM `user` WHERE email=? AND username=?";
    
    if ($stmt = $connect->prepare($query)){
    
            $stmt->bind_param("ss", $email, $uname);
    
            if($stmt->execute()){
                $stmt->store_result();
    
                $email_check= "";
    
                // Number of binded results must match the number of columns in SELECT
                $stmt->bind_result($email_check, $username_check); 
                $stmt->fetch();
    
                // or num_rows >0
                if ($stmt->num_rows == 1){
                    echo "That records already exists.";
                    exit;
                }
    
            }else{ echo "Error: " . mysqli_error($connect); }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 python进程启动打包问题
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题