Saman Rahabi
Saman Rahabi

Reputation: 15

Undefined offset: -1 PDO in for loop

I use pdo to connect mysql database and with PDO::FETCH_ASSOC function .. fetch ASSOC array..

But when run the code give this error in multi lines.

Undefined offset: -1 or Undefined offset: 61

if($pays[$i]['price'] < $pays[($i-1)]['price'])

and

elseif($pays[$i]['price'] > $pays[($i-1)]['price'])

and

.$pays[$i]['price'].

My full code

<?php

$params        = null; //or any params
$mrkfPDO       = new PDO('mysql:host=localhost;dbname=usd', 'root', '', array(
    PDO::ATTR_PERSISTENT => true,
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
));
$mrkfStatement = $mrkfPDO->prepare("SELECT price FROM uds limit 0,100");
$mrkfStatement->execute($params);
$pays = $mrkfStatement->fetchAll(PDO::FETCH_ASSOC);

for ($i = 0; $i <= count($pays); $i++) {

    $color = 'black';

    if ($pays[$i]['price'] < $pays[($i - 1)]['price'])
        $color = "red";
    elseif ($pays[$i]['price'] > $pays[($i - 1)]['price'])
        $color = 'green';
    else
        $color = 'black';

    echo "<tr>
                        <td>
                            <span style='color: $color'>" . $pays[$i]['price'] . "</span>
                        </td>
                      </tr>";
}

?>

Upvotes: 1

Views: 541

Answers (2)

Norbert
Norbert

Reputation: 6084

You loop

        for($i=0; $i<=count($pays); $i++)

starts at $i=0.

Then you try this:

          if($pays[$i]['price'] < $pays[($i-1)]['price'])

There is a $pays[($i-1)]. That is your unknown index -1 ($i-1 (or 0-1 for the first loop))

Upvotes: 1

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

The problem is $i = 0. first time $i = 0 hens $pays[($i-1)]['price'] gives -1 index which is always an offset error. Do like below :-

for($i=1; $i<count($pays); $i++) // see the change

Upvotes: 0

Related Questions