0

I'm trying to find out if the title someone filled in in a form is already in the database (cause otherwise I'm going to add a number to the title). But somehow the code underneath always give back "doesn't exists".

[my_table_name] is of course changed by the correct table name. Anyone knows what can be the problem?

$title = $_POST["title"]; 
$sql = "SELECT * FROM [my_table_name] WHERE title=$title";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)>0) {
  echo "exists";
} else {
  echo "doesn't exist";
}

2 Answers2

0

Your SQL. Add single quotes on $title:

$sql = "SELECT * FROM [my_table_name] WHERE title='$title'";
deChristo
  • 1,860
  • 2
  • 17
  • 29
0

Don't have a comment previlege hence writing here. The problem looks like that you haven't enclosed the single quotes as title is a string so it should be in the following way

$title = $_POST["title"]; 
$sql = "SELECT * FROM [my_table_name] WHERE title='$title'";
$result = mysqli_query($sql) or die(mysqli_error($con));
if(mysqli_num_rows($result)>0) {
  echo "exists";
} else {
  echo "doesn't exist";
}

Also put the die statement so that if there is an error, it will halt the execution.

Thanks

pravindot17
  • 1,199
  • 1
  • 15
  • 32