开发者

Using a Loop Inside a Function

开发者 https://www.devze.com 2023-01-04 21:33 出处:网络
I\'m still learning functions and how they work. I know what I\'m doing wrong just not how to fix it. I am writing a function to pull image data out of a database and return it onto the screen. It wor

I'm still learning functions and how they work. I know what I'm doing wrong just not how to fix it. I am writing a function to pull image data out of a database and return it onto the screen. It works but if there is more than one image it will return the last image only. I know the problem is that $project_image is only returning the last image because of the way the while loop works but my question is how can i either not use a while loop or make it add more than one image to the $project_image variable.

Abridged Function

   function get_project_image($id,$type="thumb",$src="false",$limit=1){
    if($type =="main"){
        $project_image_qry = mysql_query(" SELECT i_name FROM `project_images` WHERE i_project_id = '$id' AND i_type= '2' LIMIT $limit " ) or die(mysql_error());
        $project_image="";
            while($project_image_row = mysql_fetch_array($project_image_qry)) {
            $project_image_result =  mysql_f开发者_StackOverflow社区etch_array ($project_image_qry);    

                if($src=="true"){
                    $project_image .= '<img src="'.admin_settings('site_url').admin_settings('image_main_dir').'/'.$project_image_result['i_name'].'" alt="project_image"/>';   
                    }
                else{
                    $project_image .= $project_image_result['i_name'];
                    }
            }
        }
    return $project_image;
    }


Your while condition is fine, but you seem to be fetching twice, in $project_image_row and $project_image_result, so you're going to be skipping every other image. Just fetch the array once (in the while loop is good), and use $project_image_result instead of $project_image_row within the loop to refer to that array:

while($project_image_result = mysql_fetch_array($project_image_qry)) {
    if($src=="true"){
        $project_image .= '<img src="'.admin_settings('site_url').admin_settings('image_main_dir').'/'.$project_image_result['i_name'].'" alt="project_image"/>';   
    }
    else{
        $project_image .= $project_image_result['i_name'];
    }
}

Also, it seems like by default you told it to only request one image from the database. You have a default parameter $limit=1, and you use an SQL LIMIT to filter the results, so unless you pass a fourth argument to get_project_image the mysql_query is only going to return one result (you didn't include the call to get_project_image, so I'm not sure if you handled that or not

0

精彩评论

暂无评论...
验证码 换一张
取 消