Sol Sol - 2 months ago 9
PHP Question

How do you pull specific row index numbers from an array with FOR loops?

I am not sure what I am doing wrong. The $numrows shows rows being counted, but nothing shows for the $Value1 $Value2 $Value3.



try {
$dbh = new PDO("mysql:dbname=database;host=localhost", username, password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT id
FROM table";

$result = $dbh->query($sql);
$numrows=$result->rowCount();
echo "Total ids found $numrows";

if ( $numrows > 0 )
{
for ($i = 0; $i < count($result); $i++) {
$Value1 = $result[$i]['id'];
$Value2 = $result[$i + 1]['id'];
$Value3 = $result[$i + 2]['id'];
echo "Value1: $Value1 Value2: $Value2 Value3: $Value3";
}

Print '<br> test output';
}

Answer

You are iterating indexes multiple times :

on the first run :

$i = 0;

$Value1 = $result[0]['id'];
$Value2 = $result[1]['id'];
$Value3 = $result[2]['id'];

on the second run :

$i = 1;

$Value1 = $result[1]['id'];
$Value2 = $result[2]['id'];
$Value3 = $result[3]['id'];

etc.

You could do :

for ($i = 0; $i < count($result); $i+=3)
Comments