I use this code to check if an entry already exsists but it seems like the query always returns true. When i use the same query on shell it works properly. Have in mind that foodname is Primary Key.
$query = "SELECT EXISTS ( SELECT * FROM Food WHERE foodname = '$food_name')";
$result = pg_query($conn,$query) or die("Query could not be executed");
if($result)
{
echo 'food already exists: ';
echo $food_name;
printf("\n");
}
else
{
echo 'new food inserted';
printf("\n");
$query = "INSERT INTO food VALUES ('$food_name','$food_price','$food_date')";
$result = pg_query($conn,$query) or die("Query could not be executed");
}
QUESTION: I modified it just like 'download download' said and it works as it also works with Kettners answer but isn't EXISTS faster for checking if an entry already exists for the reason that it stops when it finds a pair? Is there any query using EXISTS that can work in this case? Thnx for the help.
ANSWER: After reading everything you guys said the following one is what i choosed to use,it works and also uses EXISTS.
$query = "SELECT 1 FROM food WHERE EXISTS ( SELECT * FROM Food WHERE foodname = '$food_name')";
$result = pg_query($conn,$query) or die("Query could not be executed");
$row = pg_fetch_row($result);
if($row[0])
{
echo 'food already exists: ';
echo $food_name;
printf("\n");
}
else
{
echo 'new food inserted';
printf("\n");
$query = "INSERT INTO food VALUES ('$food_name','$food_price','$food_date')";
$result = pg_query($conn,$query) or die("Query could not be executed");
}