Lucy Weatherford
Lucy Weatherford

Reputation: 5544

php - checking whether a variable is set/ is true/ exists

In my code I am checking whether variables exist. But it is not turning out the way I expect it.

This is what I'm trying to do:

  1. Retrieve $result from database.
  2. Execute a block of code only if a result has been extracted (otherwise do nothing/skip over/move forward).

I used if(isset($result)) but it doesn't seem to be working, looks like the if is being executed, even though it shouldn't when there is no data in $result. (but with problems because there is no actual $result variable to use in this block)

Upvotes: 1

Views: 970

Answers (5)

Vishnu
Vishnu

Reputation: 2110

To check if there is any data extracted, use this :

$connect = mysql_connect("127.0.0.1",$sql_username,$sql_password);
$data = mysql_query($sql_query,$connect);
$result = mysql_fetch_array($data);
if($result) { ... }

Upvotes: 1

koen
koen

Reputation: 13767

If you use something like mysql_query it will return a resource, or false on error. That means it will always be set.

Upvotes: 1

span
span

Reputation: 5628

Isset only works for non instantiated variables. When you set $result to the db response you are actually setting the variable.

You could instead use mysql_fetch_assoc ( resource $result ) or mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] ) depending on what you want to do. Both of those functions will return false if there is not a response.

http://www.php.net/manual/en/function.mysql-fetch-assoc.php http://www.php.net/manual/en/function.mysql-fetch-array.php

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

Doesn't just if($result) work for you? If you have error reporting showing E_NOTICEs, then try if(isset($result) && $result)

Upvotes: 3

user142162
user142162

Reputation:

Depending on how you are executing your query, there's a possibility you should be using empty() in place of isset().

From the documentation:

isset
Determine if a variable is set and is not NULL.

empty
Determine whether a variable is considered to be empty.

For example:

$var = '';

isset($var) would return true as it has been set, but empty($var) would return false because its value is an empty string.

Upvotes: 2

Related Questions