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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里