如何使用php PDO从mysql数据库中检索和显示数据?

时间:2013-02-13 09:26:47

标签: php mysql

如何使用php PDO从mysql数据库中检索和显示数据? 这是我的代码。我知道如何使用mysql_函数来完成它。 这是我尝试过的,但到目前为止它没有显示任何内容。

 #query to display the users 
$select_all=("select * from tish_user
inner join tish_clientinfor on  tish_user.user_id = tish_clientinfor.user_id
inner join tish_images on  tish_user.user_id = tish_images.user_id
inner join tish_security on  tish_user.user_id = tish_security.user_id");
$result = $con->query($select_all);
#if the statement is success full
if($result !== false ){
$cols = $result->columnCount();
#echo number of rows 
echo 'num rows'.$cols.'</br>';
#pass the result set 
foreach($result as $row){
echo  $row['username'].'</br>';
}
}
?>

2 个答案:

答案 0 :(得分:2)

准备之后,你需要执行。

像这样:

$all->execute();

之后,循环结果:

while( $row = $all->fetch() )
    print_r( $row );

您还可以将PDO::FETCH_ASSOC提供给关联结果的fetch语句。

while( $row = $all->fetch(PDO::FETCH_ASSOC) )
    print_r( $row );

答案 1 :(得分:2)

试试这个答案

$sql = ("select * from user");
$result = $con->$query($sql);
#if the statement is success full
if ($result) !== false ){
$cols = $result->columnCount();
#echo number of rows 
echo 'num rows'.$cols.'</br>';
#pass the result set 
foreach($result as $row){
echo     $row['username'].'</br>';
}