-1

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

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Timothy Wong
  • 689
  • 3
  • 9
  • 28

2 Answers2

1

"@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); }
    }
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

Well, you are checking if the query executes, but you are not checking if the values returned are correct or not. What you need to do is verify how many rows are returned after executing the query, if a row is returned the user has been found. You can do that with num_rows.

Dante
  • 1