输出数据库中的表格的内容(pdo连接)

1。创建 pdo对象,建立连接,记得抛出异常的处理

    try{
        $pdo= new PDO("mysql:host=localhost;dbname=****;port=3306;charset:utf8",'root','*****');
        $pdo->query("set names utf8");

}catch (PDOException $e){
    echo   "连接数据库失败:".$e->getMessage();
}

2.执行sql语句,并且将结果返回给一个变量$statement

query执行一条SQL语句,如果通过,则返回一个PDOStatement对象。PDO::query函数有个“非常好处”,就是可以直接遍历这个返回的记录集。

select的话就是建议使用query来执行数据库的语句

$statement=$pdo->query("
       select id, number, value,time from sensor_data
    ");

3.将查询出来的结果赋予一个数组, 然后通过list()的方法将数组的内容给变量

  在通过一个循环,输出的数据库表格中的所有的内容

  *注意:在php中输出的html代码的时候注意格式i

while(list($id,$number,$value,$time)=$statement->fetch(PDO::FETCH_NUM))
{
    //echo   $id;

   echo  '<tr><td>'.$id.'</td>';//注意php变量要加上‘. 变量 .’
    echo   '<td>'.$number.'</td>';
    echo   '<td>'.$value.'</td>';
    echo   '<td>'.$time.'</td></tr>';



}

 

结果:

 

 

 

阅读所有的代码:

<?php

    header("content-type:text/html;charset=utf-8");
    try{
        $pdo= new PDO("mysql:host=localhost;dbname=****;port=3306;charset:utf8",'root','*****');
        $pdo->query("set names utf8");


}catch (PDOException $e){
    echo   "连接数据库失败:".$e->getMessage();

}
echo "<table border='1'  width='90%' align='center'>";
echo '<tr bgcolor="#cccccc">';
echo '<caption>sensor_data表格</caption>';
echo  '<th>ID</th><th>数字</th><th>数值</th><th>时间</th></tr>';


$statement=$pdo->query("
       select id, number, value,time from sensor_data
    ");
//$statement->execute();


while(list($id,$number,$value,$time)=$statement->fetch(PDO::FETCH_NUM))
{
    //echo   $id;

   echo  '<tr><td>'.$id.'</td>';
    echo   '<td>'.$number.'</td>';
    echo   '<td>'.$value.'</td>';
    echo   '<td>'.$time.'</td></tr>';



}
echo  '</table>';

 

posted @ 2017-05-23 17:26  阿鸠  阅读(1985)  评论(0编辑  收藏  举报