我不确定我做错了什么。 $ numrows显示计数的行,但$ 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';
}
答案 0 :(得分:1)
您正在多次迭代索引:
第一次运行:
$i = 0;
$Value1 = $result[0]['id'];
$Value2 = $result[1]['id'];
$Value3 = $result[2]['id'];
第二轮:
$i = 1;
$Value1 = $result[1]['id'];
$Value2 = $result[2]['id'];
$Value3 = $result[3]['id'];
等
你可以这样做:
for ($i = 0; $i < count($result); $i+=3)
答案 1 :(得分:0)
query
不适用于此FOR循环。您必须使用fetchAll
。使用“业余”优秀的计数代码,我们可以完成以下代码:
$sth = $db->prepare($sql);
$sth->execute();
$result = $sth->fetchAll();
/* Fetch all of the remaining rows in the result set */
//print_r($result); //check to see an actual array
//var_dump($result);
$numrows=count($result);
echo "Total ids found $numrows<br>";
if ( $numrows > 0 )
{
for ($i = 0; $i < count($result); $i+=3)
{ $Value1 = $result[$i]['course_name'];
$Value2 = $result[$i + 1]['course_name'];
$Value3 = $result[$i + 2]['course_name'];
echo "Value1: $Value1 Value2: $Value2 Value3: $Value3<br>";
}
}