Foreach和DISTINCT具有函数PHP mysql

时间:2012-05-25 11:33:40

标签: php mysql foreach distinct

我正在尝试使用foreach函数但是收到错误。这是我的代码:

function student_image_list(){
    global $host, $dbname, $user, $pass;
    $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $STH = $DBH->query("SELECT DISTINCT folder_name from school_students_images");
    $STH->setFetchMode(PDO::FETCH_ASSOC);
    $row = $STH->fetch();
    return $row;
}

我想打印表school_students_images中的所有唯一文件夹名称,我正在尝试这样做:

$folder_name1 = student_image_list();
foreach($folder_name1['folder_name'] as $folder_name)  
    { 
        echo ' <div class="mws-panel grid_2">
               <div class="mws-panel-header">
               <span>'.$folder_name.'</span>
               </div>                            
               </div>';
    }

错误 警告:第41行的student_image_list_raw.php中为foreach()提供的参数无效 这一行的错误

foreach($folder_name1['folder_name'] as $folder_name)  

请帮忙。

1 个答案:

答案 0 :(得分:1)

您只获取一行,而且似乎没有&#39; folder_name&#39;关键,你必须

function student_image_list(){
    global $host, $dbname, $user, $pass;
    $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $STH = $DBH->query("SELECT DISTINCT folder_name from school_students_images");
    $STH->setFetchMode(PDO::FETCH_ASSOC);
    return $STH;
}

$STH = student_image_list();
while (($row = $STH->fetch()) !== false) {
    echo ' <div class="mws-panel grid_2">
           <div class="mws-panel-header">
           <span>'.$row['folder_name'].'</span>
           </div>                            
           </div>';

}