0

I am trying to check if an input value already exists in my database.

So far I got the following but this always returns me "Invalid" (even if I enter a matching value) so my guess is I have an error in the part after my SELECT query or in my If Else logic.

Can someone tell me how to do this right?

My JS:

$('#btnCheck').click(function() {   
    var username = $('#username').val();

    $.ajax({
        url: 'userSubmit.php',
        type: 'POST',
        data: {username: username},
        success: function(response){
            if(response == 'valid') {
                alert('Valid');
            } else {
                alert('Invalid');
            }
        }
    });
});

My PHP:

$username = $_POST['username'];      
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
    die("Connection Error: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT username FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();

if($stmt->num_rows > 0) {
    echo "valid";
} else {
    echo "invalid";
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
keewee279
  • 1,656
  • 5
  • 28
  • 60
  • What's the actual value of `$stmt->num_rows` ? – Ing. Luca Stucchi Oct 16 '19 at 11:14
  • Have you watched the request/response in the browser's developer tools to see what is actually returned? – Jay Blanchard Oct 16 '19 at 11:14
  • It is a very bad idea to use `die($conn->connect_error);` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Oct 16 '19 at 17:45
  • One final note on your recent question. you don't use while on arrays. with fetch_all you have to use foreach – Your Common Sense Oct 26 '19 at 10:17

2 Answers2

2

There is no reason to use num_rows, which not only is confusing, easy to misuse, but also could cause performance issues if misused.

Just fetch COUNT(1) and then fetch a single column from the first row in your SQL result.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($host, $username, $password, $database);
$conn->set_charset('utf8mb4');

$stmt = $conn->prepare("SELECT COUNT(1) FROM users WHERE username = ?");
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
$exists = $stmt->get_result()->fetch_row()[0];

if($exists) {
    echo "valid";
} else {
    echo "invalid";
}

If you wanted for some strange reason to stick with num_rows you would either have to call store_result() on the statement and then get the num_rows from the statement or call get_result() and read the value of num_rows on the returned result set.

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

You need to call store_result() in order for the number of rows to actually be recorded before calling num_rows:

...
$stmt->execute();
$stmt->store_result();

if($stmt->num_rows > 0) {
    ...

The reason why you must call store_result() is that without this, no results have actually been fetched, and the number of rows (num_rows) will therefore be 0.

Reference the official documentation for num_rows:

Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.

A link to this is here.

Martin
  • 16,093
  • 1
  • 29
  • 48
  • Thanks a lot. This is exactly what was missing here ! One more question: It still does not recognise my result as this seems to contain a symbol in front of the text that I echo in PHP ("valid" / "invalid"). When I alert it in JQuery it shows me this symbol in front of my text. How can I get rid of this so that the result is only my text ? – keewee279 Oct 16 '19 at 11:20
  • @keewee279 Regarding your other question, I think that is probably worth asking separately. However, it'd be very odd to have a symbol\character appearing before your return values if you have not `echo`'d it in the PHP code. Make sure to include an example in your new question please – Martin Oct 16 '19 at 11:22
  • It still returns me Invalid as per my comment before. I only see a differece now when alerting the result but otherwise still get Invalid for any value. – keewee279 Oct 16 '19 at 11:27
  • 1
    @keewee279 That's odd. Have you tried dumping the value of `num_rows` in your PHP to see what it contains? The SQL statement should return at least 1 row if the username matches – Martin Oct 16 '19 at 11:29
  • @keewee279 I've also noticed that you are reusing the `$username` variable for both the `$_POST` output and also your `$conn`. Could that be complicating the issue? – Martin Oct 16 '19 at 11:30
  • Yes, it seems to return me spaces or some other invisible characters in front of my text so e.g. instead of "Invalid" it returns " invalid". I don't see where this could happen. It actually contains more than one space, this just gets removed on the site here. – keewee279 Oct 16 '19 at 11:31
  • 1
    It seemed I had to trim the output, not sure why but then it works with your solution so I'll accept it now. Thanks again for your help ! – keewee279 Oct 16 '19 at 11:44