Question

I am having this variable to store the result of a function: $var check=mailExists($email,$link). It is supposed to be either 1 or 2 but it would always return 1... The $email is the passed value to be checked at the DB, $link is a mysqli handler to work with. I am also printing the result of the fetch at 'rowsDEB', which always shows 0. Here's my function:

function mailExists($email, $link){
    $stmt = "";
    $result = 1; //no such mail
    $stmt = "SELECT email FROM users WHERE email = '$email'";
    mysqli_query($link,$stmt);
    mysqli_stmt_store_result($stmt);
    mysqli_stmt_bind_result($stmt);

    $rows = 0;
    while(mysqli_stmt_fetch($stmt)){
        $rows++;    
    }
    $_SESSION['rowsDEB'] = $rows;
    if(rows != 0) $result = 2; //mail exists in DB

    mysqli_stmt_free_result($stmt);
    mysqli_stmt_close($stmt);
    discDB($link);
    return $result; 
}
Était-ce utile?

La solution 2

I don't know if this code has something wrong with it but I've changed it, along with some other fixes in other functions and now all works just fine. Also I noticed i am missing a $ at if(rows != 0) $result = 2; //mail exists in DB so this may have caused the problem. Found it after I changed everything... Posting only the function code:

function mailExists($email, $link){
    $result = false; //no such mail
    $query= "SELECT email FROM users WHERE email = '$email'";
    if($stmt = mysqli_prepare($link,$query)){
        mysqli_execute($stmt);  
        mysqli_stmt_store_result($stmt);
        $rows = mysqli_stmt_num_rows($stmt);
        mysqli_stmt_free_result($stmt);
        mysqli_stmt_close($stmt);
}

$_SESSION['rowsDEB'] = $rows;
if($rows > 0) $result = true; //mail exists in DB

return $result; 

}

Autres conseils

I am assuming your $link is basically a database connection variable. This is simple but helpful mysqli example using oject oriented approach. Use select count only in your sql statement, it is more efficient.

<?php
function mailExists($email, $link){
    $sql= "SELECT COUNT(email) FROM users WHERE email = ? "; // use parameterized query
    $stmt = $link-> prepare($sql);
    $stmt -> bind_param('s',$email); // bind your variable to parameter
    $stmt -> execute(); // execute the query
    $stmt -> bind_result($CounterResult); // bind result into variable
    $stmt -> store_result();
    $stmt -> fetch();
}

return $CounterResult; // return total rows found
?>

I took the example from here. There are some more examples which might help you out. Hope this can help anybody out there, thank you.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top