我无法从数据库mysql pdo php中检索数据

时间:2013-02-16 12:52:09

标签: php pdo

我试图检查一下我的代码没有显示数据库数据的原因,但似乎我不能。数据库中有数据但是没有显示

<?php
    try {
    $con = new PDO('mysql:host=localhost;dbname=tish_database;charset=utf8','root','');
    echo "we connected" ;
    } catch(PDOException $e){
    echo 'Connection failed'.$e->getMessage();
    }

    ?>
    <?Php

    $query ="select date_created from tish_user";
        $result= $con->prepare($query);
        $result->execute();
        while($row = $result->fetch(PDO::FETCH_ASSOC)){
    echo $row['date_created'];

    }
    ?>

1 个答案:

答案 0 :(得分:2)

$con = new PDO('mysql:host=localhost;dbname=tish_database;charset=utf8','root','');
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

查看错误。

您的查询中存在错误,from

之前没有空格

(我也在DSN中更改了charset以更正mysql拼写)

更一致的代码版本:

$dsn = 'mysql:host=localhost;dbname=tish_database;charset=utf8';
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$con = new PDO($dsn,'root','', $opt);

$sql = "SELECT date_created FROM tish_user";
$stm = $con->prepare($query);
$stm->execute();
while($row = $stm->fetch()) {
    echo $row['date_created'];
}