douhuai2015 2014-02-18 14:47
浏览 110
已采纳

使用PDO从数据库中选择数据

I have some data in a mysql database.The database every time consists of a different number of rows.

An example of my table would be :

id  team1  team2  home  away  tip
----------------------------------
12   xxx    yyy   zzz   kkk
43   xxx    yyy   zzz   kkk
.     .      .     .     .
.     .      .     .     .

So what i need to do is loop through every row of the table and be able to get the data from that row so i can create the tip.

I am a bit confused on how i could do that with pdo.

What i ve tried so far is try to get a column of data like this:

$stmt = $db->prepare("SELECT id FROM tablename");
    $stmt->execute();
    $result=$stmt->fetchColumn();
    echo $result[0];

But even that , that i would expect to give me back the first id , which is 12 in this case, just returns me 1. Any ideas here?

  • 写回答

5条回答 默认 最新

  • doujia4759 2014-02-18 14:58
    关注
    $stmt = $db->prepare("SELECT id FROM tablename");
    try{
        $stmt->execute();
    }catch(PDOException $err){
        //some logging function
    }
    //loop through each row
    while($result=$stmt->fetch(PDO::FETCH_ASSOC)){
        //select column by key and use
        echo $result['id'];
    } 
    

    alternatively you could use fetchAll to select whole dataset into a variable. Then you wouldn't need to loop

    Heres a useful resource for PDO:

    http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用