PHP isset() function returns FALSE even though the variable is defined

Let’s say we have a table item in a MySQL database, with the primary key iditem and a field code that can be NULL:

CREATE TABLE `item` (
`iditem` int(10) unsigned NOT NULL,
`code` VARCHAR(10) DEFAULT NULL,
PRIMARY KEY (`iditem`),
);

--
-- Dumping data for table `item`
--

INSERT INTO `item` (`iditem`, `code`) VALUES
(1, 'as1435v'),
(2, NULL),
(3, 1, 'YHryt4t90');

In PHP we define a variable $item_code that we initialize with 0 and then we run a query for setting the value of $item_code to the code of the item which has the id 2 in our database:

$item_code = 0;
$query = "SELECT code FROM item WHERE iditem = 2";
$result = mysql_query($conn); //$conn is our database connection
if($result) {
	if($row = mysql_fetch_row($result)) {
		$item_code = $row[0];
	}
}

if(isset($item_code)) {
	echo "item code: ".$item_code;
} else {
	echo "item code is not set";
}

The output will be:
item code is not set

That is because the code is NULL in the database and it is transferred into PHP not as the empty string, but as NULL.
And the name of the isset() function is misleading as it returns FALSE not only when a variable is not defined, but also when a variable has been set to NULL.

Leave a Reply

Your email address will not be published. Required fields are marked *