dongliyi967823 2014-10-17 11:04
浏览 271
已采纳

如何从php中获取数据库中的所有数据

Here is my code:

<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=sample", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database <br />';

$sql = "SELECT * FROM sampletable";

$stmt = $dbh->query($sql);
$result = $stmt->fetch(PDO::FETCH_ASSOC);

foreach($result as $key =>$val){

echo $key. '-' .$val.'<br />';

}
$dbh = null;

    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?>

Now i am learning php, I want know about pdo connection to insert,update fetch data from database. I referred this link http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#7.1

Now i got first column value.. May i know how to fetch all the records from database?

Thanks in advance.

  • 写回答

4条回答 默认 最新

  • douxing8855 2014-10-17 11:08
    关注

    You could just use ->fetchAll() method with this:

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC); // returns all rows
    foreach($result as $key => $row) {
        echo $row['id'] . ' - ' . $row['column_name'] . '<br/>';
                         // ^ name of the column, this returns a multi dimensional
    }
    

    Sidenote: Its still an array inside, so you need to access the index of that copy inside the foreach.

    Or also like this:

    while($row = $result->fetch(PDO::FETCH_ASSOC)) {
        echo $row['id'] . ' - ' . $row['col1'] . '<br/>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题