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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题