-1

In my code I have a bunch of if-clauses that check wether a user given input is valid to be inserted in to the database. Now there's one little if clause, which I want to check wether the userinput is the same as a given string from the database. I've been trying for a day now what my mistake is and I just can't seem to find a solution.

$car = $_POST['car'];
$exists = mysqli_query("SELECT car FROM box WHERE car = '".$car."' AND del = 0;");

if($car == $exists) { //same string, give error1 } else { give error2 }

I have no clue what the problem could be as '==' is supposed to be case sensitive and as far as I was able to find out you can compare strings in variables like this.

CarlosAS
  • 654
  • 2
  • 10
  • 31
LM31
  • 1
  • 3
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Jul 26 '16 at 12:59
  • 4
    Look at what `mysqli_query()` actually returns [In the ??? Manual of all the odd places](http://php.net/manual/en/mysqli.query.php) – RiggsFolly Jul 26 '16 at 12:59
  • 1
    `$exists` is just a resource, you still have to fetch the data from the query. – Jay Blanchard Jul 26 '16 at 12:59
  • Since you are using `WHERE car = ...`, `$exists->num_rows` will do the job ! – Ismail RBOUH Jul 26 '16 at 13:01
  • Thanks people. I'm just getting a hold of php and MySQL so I didn't know I had to additionally fetch the data. I ended up using the function mysqli_fetch_assoc. – LM31 Jul 26 '16 at 14:04

1 Answers1

0

To avoid sql injection you should better use prepared statement.

And to check if query returns any rows you can check num_rows property.

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$carFound = false; 
if ($stmt = $mysqli->prepare("SELECT car FROM box WHERE car = ? AND del = 0")) {
    $car = $_POST['car'];
    $stmt->bind_param("s", $car);
    if ($stmt->execute() && $stmt->num_rows>0) {
        $carFound = true;
    }
}

//if (carFound)  { same string, give error1 } else { give error2 }
Alex
  • 16,739
  • 1
  • 28
  • 51