I need to check my db to see if a username or email is already in use

208 views Asked by At

I've started a thread or two so far but nothing has got resolved. I'm not able to use the mysqlnd because i'm using a shared hosting account with godaddy.

All i need to do is check if my email address and/or username is in use; if they are in use throw and error, if not.. all is well.

Here is my code:

$input_errors = array();

if (!empty($_POST['username'])) {
    $user = $_POST['username'];
} else {
    $input_errors['username'] = "Must fill out username";
}

$email = filter_input(INPUT_POST, 'usermail', FILTER_VALIDATE_EMAIL);
if (false === $email) {
    $input_errors['usermail'] = "Not a valid email address";
}

if(count($input_errors) > 0) {
    print_r($input_errors); die();
}

$sql = "SELECT COUNT(*) as amount FROM people WHERE username = ? 
       OR email = ?";
if ($stmt = $mysqli->prepare($sql)) {

    $stmt->bind_param("ss", $user, $email);
    $stmt->execute();
    $results = $stmt->get_result();
    $data = mysqli_fetch_assoc($results);

    if ($data['amount'] > 0)
    {
        print "User already exists";
    }
}

else {
$stmt = $mysqli->stmt_init();
if (!$stmt) {
    echo "Init failed";
} else {
    $cmd = "INSERT INTO people (username, email, sign_up_date) VALUES (?, ?, NOW() )";
    if ($stmt->prepare($cmd)) {
        $stmt->bind_param('ss', $user, $email );
        $stmt->execute();

        echo $stmt->affected_rows . " row(s) inserted";

        $stmt->close();

    } else {
        echo "Prepare failed";
    }
    mysqli_close($mysqli);
    }
}

bind_result() does not work.

1

There are 1 answers

1
AudioBubble On

Change your sql statement to the following:

$sql = "SELECT COUNT(*) as amount FROM people WHERE username = '".mysqli_real_escape_string($_POST['username'])."' OR email = '".mysqli_real_escape_string($email)."'";