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条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?