Page 1 of 1

conditional code causes undefined property error

Posted: Wed Jan 06, 2010 11:35 pm
by kevinwinters
Hi,
I am trying to add an if statement to my select statement in MYSQL but I keep getting a "Notice: Undefined property: stdClass::$date_sold " error when I try.

Here is the code snippet that works fine:

Code: Select all

 
$sql = "
    SELECT 
        i.id,
        i.name,
        i.featured_item,
        i.sales_status,
        c.name room_type,
        im.name image,
        i.date_added,
        i.date_last_modified,
        i.date_sold
    FROM 
        inventory i
etc.....
 
 
But when I try to do this

Code: Select all

 
$sql = "
    SELECT 
        i.id,
        i.name,
        i.featured_item,
        i.sales_status,
        c.name room_type,
        im.name image,
        i.date_added,
        i.date_last_modified,
        CASE i.date_sold
              WHEN '0000-00-00 00:00:00' THEN 'Not Sold'
        END
    FROM 
        inventory i
 
I get the error

I am just trying to display something else on my PHP page if the datetime field is '0000-00-00 00:00:00'

Could anyone help with this?


Thanks in advance

Re: conditional code causes undefined property error

Posted: Wed Jan 06, 2010 11:48 pm
by pbs
You can try IF statement like this

Code: Select all

 
$sql = "SELECT i.id, i.name, i.featured_item, i.sales_status, c.name room_type, im.name image, i.date_added, i.date_last_modified, IF(i.date_sold = '0000-00-00 00:00:00', 'Not Sold', '') FROM inventory i
 

Re: conditional code causes undefined property error

Posted: Thu Jan 07, 2010 1:02 am
by requinix
You probably need an alias. Using pbs's modification,

Code: Select all

SELECT i.id, i.name, i.featured_item, i.sales_status, c.name room_type, im.name image, i.date_added, i.date_last_modified, IF(i.date_sold = '0000-00-00 00:00:00', 'Not Sold', '') AS date_sold FROM inventory i

Re: conditional code causes undefined property error

Posted: Thu Jan 07, 2010 1:36 am
by Eran
The error notice you are seeing has nothing to do with the SQL statement.
Notice: Undefined property: stdClass::$date_sold
You are trying to access a property called date_sold on an object somewhere in your code, and that property is not declared.

Regrading your case statement, you are missing an ELSE condition - if no condition matches the case, MySQL will return a "Case not found" error.
[sql]SELECT         i.id,         i.name,         i.featured_item,         i.sales_status,         c.name room_type,         im.name image,         i.date_added,         i.date_last_modified,         (CASE i.date_sold               WHEN '0000-00-00 00:00:00' THEN 'Not Sold'               ELSE i.date_sold         END) AS date_sold     FROM         inventory i[/sql]
http://dev.mysql.com/doc/refman/5.0/en/ ... ement.html

Re: conditional code causes undefined property error

Posted: Thu Jan 07, 2010 8:08 am
by kevinwinters
Thank You,

That worked without an error