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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog