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