PHP-尝试将Mysqli转换为PDO [英] PHP- Trying to convert Mysqli to PDO

查看:97
本文介绍了PHP-尝试将Mysqli转换为PDO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Mysqli代码转换为使用PDO

I am trying to convert the Mysqli code to use PDO

Mysqli代码如下所示(效果很好)

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>";                   
        }


我尝试过的PDO代码


My PDO code I tried

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

我应该如何在此处编写while循环

How should I write a while loop here

在w3schools网站上,给出的使用PDO检索记录的信息如下,该信息未说明什么是V,也未说明如何从表中检索字段codeusername.

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;
    }

推荐答案

这是从数据库中选择数据的可怕方法.它比必需的要复杂得多.我想它可能在某些情况下可能有用,但在这里没有用.

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.

简单的方法是使用 PDOStatement::fetch .其工作方式与mysqli_fetch_assoc大致相同. (虽然没有结果,但您可能还需要其他代码,因此从严格意义上讲,您不必检查行数.)

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>";                   
}

但是,我的首选方式是使用PDOStatement::bindColumn,它摆脱了数组并使用了漂亮的普通变量:

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>";                   
}

这篇关于PHP-尝试将Mysqli转换为PDO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆