警告:非法字符串偏移

时间:2014-10-29 02:52:00

标签: php arrays string oop warnings

我是oop的新手,我有一个图像显示当我有一个数组查询(仅请求图像网址)但是当我向查询数组添加第二个维度(表格中的图像ID)时我才刚刚结束收到警告消息'警告:非法字符串偏移'。我在数据库类中使用了mysqli_fetch_assoc,然后通过foreach循环运行结果。

这是我得到的信息。

提前感谢您提供的任何帮助。

页码

$user = $_SESSION['user_name'];

        $query = "SELECT gallery_image, 'gallery_id' FROM gallery WHERE user_name = '$user' ORDER BY gallery_id DESC";
        $result = $obj_db->get_gallery($query);
        foreach ($result as $image ) {
            foreach ($image as $key => $value) {
                echo '<div class="gallery_item"><a href="proof.php?image='.$value['gallery_id'].'"><img src="'.$value['gallery_image'].'"></a></div>';
            }
        }

数据库类代码

function get_gallery($sql){
        $obj_res = mysqli_query($this->obj_db_conn, $sql);
            if(mysqli_errno($this->obj_db_conn)){
                    die ("Failed query: $strSql".$this->obj_db_conn->error);
     }
        $arResults = array();
                while($arRow = mysqli_fetch_assoc($obj_res)){
                    $arResults[] = $arRow;

                }
                    return $arResults;

1 个答案:

答案 0 :(得分:1)

如果var_dump上的$result输出显示,

array(2) { 
    [0]=> array(2) { 
        ["gallery_image"]=> ""
        ["gallery_id"]=> ""
    } 
    [1]=> array(2) { 
        ["gallery_image"]=> ""
        ["gallery_id"]=> ""
    } 
} 

您的页面代码中不需要两个嵌套的foreach循环。一个foreach循环就足够了。

   $query = "SELECT gallery_image, gallery_id FROM gallery WHERE user_name = '$user' ORDER BY gallery_id DESC";
   $result = $obj_db->get_gallery($query);
   foreach ($result as $image ) {
        echo '<div class="gallery_item"><a href="proof.php?image='.$image['gallery_id'].'"><img src="'.$image['gallery_image'].'"></a></div>';
   }