seoppc
seoppc

Reputation: 2824

Getting errors on mysql returned array

We are using following code for setters.

            if (is_numeric($id)) {

            global $db;

            $product = $db->query('SELECT id, name, code, amount FROM products WHERE id = ' . $id . ' LIMIT 1');

            print_r($product);
            echo $product['name'];

            if (!empty($product)) {

                $this->cId = $product['id'];

                $this->cName = $product['name'];

                $this->cDuration = $product['code'];

                $this->cCost = $product['amount'];

            }

            else return false;

        }

    }

But its giving following output with notices...

Array ( [0] => Array ( [id] => 2 [name] => Gaming [code] => 12 [amount] => 20000 ) ) 

Notice: Undefined index: name in root//class.products.php on line 26

Notice: Undefined index: id in root/class.products.php on line 30

What are we doing wrong, please help, thanks.

Upvotes: 0

Views: 35

Answers (3)

deceze
deceze

Reputation: 522402

Your array has a nested array, so you'd need to access it using $product[0]['name']. There's still no key 'duration' or 'fee' in there though.

Upvotes: 1

Alp
Alp

Reputation: 29739

It's a subarray. You can access it with $product[0]['id'] for example `

Upvotes: 0

Mike Lewis
Mike Lewis

Reputation: 64167

$product actually contains an array of an array, in which you want to access the first one by doing $product[0]

You want to do this instead:

$product[0]['id']

$product[0]['name']

and so on.

Upvotes: 2

Related Questions