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 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler