0

I'm developing a mobile application for android and I'm trying to compare a variable on the phone to a variable already in the database, so that I can insert it if it's new and update it if it already exists.

$name_check = $_POST['Name'];

$result = mysqli_query($con, "SELECT * FROM Data WHERE Name = $name_check");
if($result && mysqli_num_rows($result) > 0)
{
// Update entry
}

This code doesn't seem to work as this block is skipped over and goes to my else block where a new entry is written, so I end up with loads of entries instead of updating one.

I have another field in the table called "Level", and when I compare against that it seems to work, which just confuses me further.

If anyone has any insight into how to do this or why it's not working for me I'd be very grateful.

Blocky
  • 40
  • 5

3 Answers3

0

Use quotes:

$result = mysqli_query($con, "SELECT * FROM Data WHERE Name = '$name_check'");
fdglefevre
  • 672
  • 4
  • 15
0

Use this:

$result = mysqli_query($con, "SELECT * FROM Data WHERE Name = '" . $name_check . "'");
Undo
  • 25,519
  • 37
  • 106
  • 129
0
$result = mysqli_query($con, "SELECT * FROM Data WHERE Name = '".$name_check."'");

This should work fine

Khan Shahrukh
  • 6,109
  • 4
  • 33
  • 43
  • 1
    All of the listed answers will work but keep in mind this is a very good case to demonstrate SQL injection. Make sure to sanitize your input values as there could be something malicious put into your form and glean information about your database. Some ways to do this are using data validation before running the insert statement or the use of prepared database statements. – Jason Bell Mar 30 '15 at 18:34