0

我正在练习使用 PDO 获取方法从表中检索数据。我想在一个while循环中设置一个计数器来一次检索一行数据。请给我一些建议如何做到这一点。谢谢!

这是我使用 PDO::Query() 和 PDO::fetch() 方法的 2 个代码示例。代码示例 1 使用 PDO::Query() 方法

$sql = 'select first_name, last_name, pd, b_month, b_day, b_year from reg_data';
$birth_date = '';
try
{
    foreach($con->query($sql) as $row)
    {
       print $row['first_name'] . "  ";
       print $row['last_name']. "  ";
       print $row['pd'] . "  ";
       $birth_date =  $row['b_month'] . "-". $row['b_day'] . "-". $row['b_year'];
       print "$birth_date";
    } 

}
catch(PDOException $e)
{
    echo " There is a problem with you db connection";
    echo $e->getMessage();
}

示例 2 使用 PDO::fetch() 方法

try {
    $con = new PDO ($dns, $db_uid, $db_pd, $option);
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "select * from reg_data";
    $stmt = $con->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt->execute();

    //using cursor to interate through array
    while($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
    {
        $data = $row[0].$row[1]. $row[2] .$row[3].$row[4].$row[5];
        print $data;
    }
   $stmt = null; //close the handle
}
catch(PDOException $e)
{
    echo " There is a problem with you db connection";
    print $get->getMessage();
}
4

2 回答 2

2

我认为你需要 PDO::fetchAll。
直接来自标签 wiki的代码示例:

//connect
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);

//retrieval
$stm = $pdo->prepare("select * from reg_data");
$stm->execute();
$data = $stm->fetchAll();
$cnt  = count($data); //in case you need to count all rows
//output
?>
<table>
<? foreach ($data as $i => $row): ?>
  <tr>
    <td><?=$i+1?></td> <!-- in case you need a counter for each row -->
    <td><?=htmlspecialchars($row['first_name'])?></td>
  </tr>
<? endforeach ?>
</table>
于 2013-03-05T13:36:58.093 回答
0

您可以使用变量并在循环中递增它

$counter++ ;
于 2013-03-05T13:37:07.080 回答