ronaldo cr
ronaldo cr

Reputation: 19

Undefined index error on php

i am getting "Notice: Undefined index: brand in C:\folder\folder\folder\folder\file.php on line 8" can some one tell me why is this ? here's my code below you can see line 8 below

<?php
require_once '../core/init.php';
$id = $_POST['id'];
$id = (int)$id;
$sql = "SELECT * FROM products WHERE id = '$id'";
$result = $db->query($sql);
$product = mysqli_fetch_assoc($result);
$brand_id = $product['brand'];
$sql = "SELECT brand FROM brand WHERE id = '$brand_id'";
$brand_query = $db->query($sql);
$brand = mysqli_fetch_assoc($brand_query);
?>

Upvotes: 1

Views: 562

Answers (1)

Markandeya
Markandeya

Reputation: 537

Let me explain the error in detail with an example.
'Undefined index' error occurred because the associative array returned by mysqli_fetch_assoc() does not contain an index named 'brand'.

So you can use var_dump() to take a peek and see the actual contents of $product variable like this, example:

<?php
$product = ['name'=>'Item1', 'price'=>10];
$anothervariable = $product['brand'];//which gives the error

//doing a var dump to see the contents of $product
var_dump($product);
?>

Output:

Notice: Undefined index: brand in /var/www/html/test/register.php on line 3 array(2) { ["name"]=> string(5) "Item1" ["price"]=> int(10) }

which obviously doesn't contain ["brand"].

Upvotes: 2

Related Questions