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 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私