Check if the username already exists with MySQLi

2019-09-18 23:58发布

问题:

I try to check if the username and email from input fields already exists in my database before to create a new user.

this is login.php :

<?php
session_start();
$pseudo = $_POST['pseudo'];
$mail = $_POST['mail'];

$pseudo=mysql_real_escape_string($pseudo);
$pseudo=ltrim($pseudo);
$pseudo=rtrim($pseudo);

$mail=mysql_real_escape_string($mail);
$mail=trim($mail);

$sql=mysqli_connect('localhost','root','','bdd_name');
$query=("SELECT COUNT(*) FROM t_people WHERE 'PEO_PSEUDO'='".$pseudo."' OR 'PEO_MAIL'='".$mail."'");
$result = mysqli_prepare($sql,$query);

    mysqli_stmt_execute($result);
    mysqli_stmt_store_result($result);

if (mysqli_stmt_num_rows($result) == 0) {
  echo 1;
 }
 else {
 echo 2;
 }
mysqli_stmt_free_result($result);
mysqli_stmt_close($result);
?>

And this is a part of my JavaScript :

var pseudo=$("#pseudo").val();
var mail=$("#mail").val();
    $.ajax({
        type: "POST",
        url: "login.php",
        data: {pseudo:pseudo, mail:mail}
        }).done(function(result) {
            if (result==1) {
                good();
            }
            else if (result==2) {
                bad();
            }
        });

Can anyone tell me what is wrong with this?

I'm on this since hours now and I'm clueless...

回答1:

There are some things going wrong. Don't use mysql_real_escape_string cause you're working with mysqli_*. Use mysqli_real_escape_string instead. But better use mysqli_stmt_bind_param because you're working with prepared statements. And if you work with COUNT(*) you always get 1 row.

$pseudo = $_POST['pseudo'];
$mail = $_POST['mail'];

$query = "SELECT * FROM t_people WHERE PEO_PSEUDO = ? OR PEO_MAIL = ? LIMIT 1";
$stmt = mysqli_prepare($sql, $query);
mysqli_stmt_bind_param($stmt, 'ss', $pseudo, $mail);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$numRows = mysqli_stmt_num_rows($stmt);
mysqli_stmt_close($stmt);

With COUNT(*) (which is more efficient) it goes like:

$query = "SELECT COUNT(*) as numrows FROM t_people WHERE PEO_PSEUDO = ? OR PEO_MAIL = ?";
...
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $numRows);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);

// work with $numRows


回答2:

You are using wrong operator for escaping use backtick operator in your query like this

"SELECT COUNT(*) FROM t_people WHERE `PEO_PSEUDO`='".$pseudo."' OR `PEO_MAIL`='".$mail."'"