dream1849 2016-12-22 15:39
浏览 105
已采纳

PHP-试图将Mysqli转换为PDO

I am trying to convert the Mysqli code to use PDO

Mysqli code looks like the following (which works great)

$rs = "SELECT * FROM team";

$result = mysqli_query($con,$rs);           
$data = mysqli_num_rows($result);
$responses = array();
    if($data != 0) {
        while($results = mysqli_fetch_assoc($result))
          {
        echo "<tr><td>".$results['code'] ."</td>";
        echo "<td>".$results['username'] ."</td>";                   
        }

My PDO code I tried

    $stmt = $con->prepare("select * from  team");
    $stmt->execute();
    if($stmt->rowCount() > 0)
 $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 

How should I write a while loop here

on w3schools website, the information given to retrieve the records using PDO is as below, which did not say what is V and doesn't say how do I retrieve the fields code and username from the table.

  foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
        echo $v;
    }
  • 写回答

4条回答 默认 最新

  • dongye9228 2016-12-22 15:48
    关注

    That's a horrifically awful way to select data from a database. It's far more complex than is necessary. I suppose it might be useful in a certain context, but not here.

    The simple way is with PDOStatement::fetch. This works in much the same way as mysqli_fetch_assoc. (You don't strictly speaking need to check the row count, though you might have other code if there are no results.)

    while ($row = $stmt->fetch()) {
        echo "<tr><td>".$row['code'] ."</td>";
        echo "<td>".$row['username'] ."</td>";                   
    }
    

    My preferred way, however, is with PDOStatement::bindColumn, which gets rid of arrays and uses nice plain variables instead:

    $stmt->setFetchMode(PDO::FETCH_BOUND);
    $stmt->bindColumn('code', $code);
    $stmt->bindColumn('username', $username);
    while ($row = $stmt->fetch()) {
        echo "<tr><td>$code</td>";
        echo "<td>$username</td>";                   
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU
  • ¥30 51单片机C语言数码管驱动单片机为AT89C52
  • ¥100 只改动本课件的 cal_portfolio_weight_series(decision_date), 跑完本课件。设计一个信息比率尽量高的策略。
  • ¥20 如何在visual studio 2022中添加ImageMagick库
  • ¥50 如何实现uniapp编译的微信小程序做可回溯视频
  • ¥15 求Houdini使用行家,付费。价格面议。
  • ¥15 前端高拍仪调用问题报错
  • ¥15 想用octave解决这个数学问题