Query returns the same result whether the record is present or not

In my controller:

public function view($id = null) {
$recipe_url = $this->fetchTable('Recipes')->find('list')->select(['url'])->where(['Recipes.user_id' => $id])->first();
$this->set('recipe_url',  $recipe_url);}

In my view template:

if (!isset($recipe_url) || empty($recipe_url) || $recipe_url="NULL" || $recipe_url="") {echo "This cook has no links to online recipes yet.";}
echo $recipe_url; //FOR TESTING

I am trying to get the record for the url field in the Recipes table but my $recipe_url query returns the number 1 whether there is an url field present or not. I would expect to get 0 if the url field isn’t set and a string if it is set but my echo $recipe_url; statement in the template prints the number 1 no matter whether the url field is set or not. And the statement “This cook has no links to online recipes yet.” prints out both when the url is set and when it isn’t set.

$recipe = $this->fetchTable(‘Recipes’)->find(‘all’)->select([‘url’])->where([‘Recipes.user_id =’ => $id])->first();
$this->set(compact(‘recipe’));

do not use list in that way, use list when you define array key and values from query use all instead

if(!empty($recipe)){
echo $recipe->url;
}

1 Like

Also, you have used = instead of == in your if statement. And quotes around NULL, which doesn’t need them. And those two comparison checks are unnecessary anyway because you’ve already checked if it’s empty.

Thanks for the code, Rods. I had to tweak it a little because the compact didn’t work. This is what worked:

if(!empty($recipe_url->url)){
echo "NOT EMPTY";
}
1 Like