-2

I'm trying to take input from form and compare to $username in database.

If the username does not exist it should print error.

elseif (($_POST['user']) != ($this->mysqli->query("SELECT * FROM users WHERE username='" . $username . "'"))) {
                  $json['message'] = "User does not exist";
                  }

This doesn't log a php error, but it doesn't work either.

flyup
  • 1
  • 1
  • 1
    The use of your SELECT in this way won't work, you need to read up on how to do a select, preferably using prepared statements. – Nigel Ren Mar 14 '18 at 15:21
  • 1
    you can't do that,the second parameter just runs the query, it doesn't acctually return any value, you have to add some sort of fetch after it – PedroFaria99 Mar 14 '18 at 15:22
  • Thanks for the help. I understand the query doesn't return a value. BUT why did user @mateus change the code in my original question? Now, this entire thread is useless. WTF? – flyup Mar 15 '18 at 15:03
  • I changed the code to: elseif ($check = $this->mysqli->query("SELECT * FROM users WHERE username='" . ($_POST['user']) . "'")); if ($check->num_rows = 0) { $json['message'] = "User does not exist"; this is the error: PHP Parse error: syntax error, unexpected '->' – flyup Mar 17 '18 at 13:19

1 Answers1

0

Make sure you're receiving the correct username through the POST request, this is a common source of errors. Just log it and check the errors file.

Then, let's analyze your mysql query:

SELECT * FROM users WHERE ...

After the select keyword, you should specify which columns you want to be returned. An asterisk (*) means you want all of them, which is fine if you have a single column, the username, but I'm assuming you have more. In this case, notice in your code that you'll be comparing a bunch of columns against the username. It will fail.

Check out this tutorial, it will be helpful to get familiar with using php plus mysql.

I wrapped the snippet below to show you a way of doing this, there are many. It is just checking if the query returned zero rows, which indicates that no record with the given username exists. A better way would be using the mysql function EXISTS().

$username = $_POST["username"];

error_log("Checking if username:'$username' exists.", 0);

$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
$sql = "SELECT * FROM users WHERE username = '$username'";
$query = $conn->query($sql);

if ($query->num_rows == 0) {

    error_log("The username does not exist.", 0);

}
Mateus
  • 2,640
  • 5
  • 44
  • 62