ForeverSJC
ForeverSJC

Reputation: 312

PHP Notice: Undefined index

I'm getting "PHP Notice: Undefined index: company" when I run a script, this is the part that is going bad, how can I fix it ?

while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
$numer = $row['fonefull']; 

$sql = "SELECT company FROM numeros.portados  WHERE number = '$numer' LIMIT 1";
$result = $conn->query($sql);
echo $sql;
$operadoraResult = $consulta->fetch(PDO::FETCH_ASSOC);

if(is_array($operadoraResult))
    $resultcompany = $operadoraResult['company'];

Thanks

Upvotes: 0

Views: 990

Answers (3)

edwardmp
edwardmp

Reputation: 6611

The array $operadoraResult does not have an element with the key company.

What happens if you change:

$result = $conn->query($sql);
echo $sql;
$operadoraResult = $consulta->fetch(PDO::FETCH_ASSOC);

if(is_array($operadoraResult))
    $resultcompany = $operadoraResult['company'];

into this:

foreach ($conn->query($sql) as $operadoraResult)
{
    if(is_array($operadoraResult))
        $resultcompany = $operadoraResult['company'];
}

Upvotes: 0

anonymous
anonymous

Reputation: 36

$operadoraResult can be an empty array if there's no company with the given number. So there won't be an index 'company'.

Try

if(!empty($operadoraResult))

Upvotes: 1

echochamber
echochamber

Reputation: 1815

Notices are kinda like warnings saying "Hey, this isn't going to cause an issue that will break anything by itself, but you might be making an assumption about a variable that is not true"

Like you may assume that a value actually exists at that index, but if the index doesn't exist you're actually getting back NULL.

You can change whether or not notices are displayed by changing the level of error reporting for php. You can do this by either editing the value of display_errors in your php.ini file or you can change in during runtime using the error_reporting function.

In this specific case its letting you know that in this line:

$resultcompany = $operadoraResult['company'];

you are trying to access an element in the array $operadoraResult at the index 'company', but there is no index that exists at 'company'.

Upvotes: 0

Related Questions