Welcome Guest, Not a member yet? Register   Sign In
How to solve "Trying to get property of non-object" error?
#1

[eluser]Sinclair[/eluser]
Hi,

I have a database query that sometimes don't return any data. I have some problems with that... shows me an error only when the query returns nothing.

Code:
A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

Filename: views/anun_view.php

Line Number: 47

I have the same error also in line 49.


This error is generated in this situation:

Code:
(line 47)    <?php if ($EstadoAnuncioPago->id_anuncio_estado == 'act') : // ?>
            <?php echo $row->telefone_anuncio; ?>
(line 49)    <?php elseif ($EstadoAnuncioPago->id_anuncio_estado == 'stoputiliz') : //  ?>
            Indisponivel
        <?php else : ?>
            <?php echo $row->telefone_anuncio; ?>
            <?php print_r($EstadoAnuncioPago); ?>
        <?php endif; ?>

The print_r($EstadoAnuncioPago) returns this:

Quote:Array ( )

How can I avoid this PHP error in the IF statements?

Best Regards,
#2

[eluser]WanWizard[/eluser]
Eh, make sure the variable contains what you think it should contain?

In this case, $EstadoAnuncioPago is an array, which you try to use as an object in the if statement. Which off course is not going to work, and PHP tells you so.

Solution: fix your error, which means: test the result of your query before you start working with the results.
Code:
$query = $this->db->get('table');
if ( $query->num_rows )
{
    // the result contains data
    foreach ( $query->result() as $row )
    {
        if ($row->my_field = 'value')
        {
            // do something
        }
    }
}
else
{
    // table contains no data
}
#3

[eluser]Sinclair[/eluser]
Thanks for the reply.

I have solved the problem with a LEFT JOIN in the SQL Query.

Best Regards




Theme © iAndrew 2016 - Forum software by © MyBB