从数据库中获取数据时,Array_push()在while循环中不起作用

时间:2017-06-06 20:20:54

标签: php sql pdo

我遇到过这个以前从未经历过的问题。 php array_push在while循环中不起作用。当我使用while循环时,浏览器上没有打印任何内容,但是当我在没有while循环的情况下获取数据时,它工作正常。我哪里可能出错。我一直在努力,似乎没有工作。

这是我的PHP代码:

function getFeaturedCrops(){
    require "config.inc.php";

    try{



        $query = $conn->prepare("SELECT * FROM crops WHERE category = ? "); 
        $query->bindValue(1, 1); 
        $query->execute(); 
        if($query->rowCount()){
            //echo "nice";

            $jsonArray = array();

            while($data = $query->fetch(PDO::FETCH_ASSOC)){
                // here we are loading either animals ar crops

                $type = $data['type'];
                $name = $data['name']; 
                $description = $data['description']; 
                $image = $data['image'];
                $id = $data['salt'];

                if(strlen($description) > 50){
                    $shortDescription = substr($description, 0, 50)."...";
                } else {
                    $shortDescription = $description; 
                }


                if(strlen($name) > 20){
                    $shortName = substr($name, 0, 20)."..."; 
                } else {
                    $shortName = $name;
                }

                if(strlen($type) > 20){
                    $shortType = substr($type, 0, 20)."...";
                } else {
                    $shortType = $type;
                }

                //echo "$shortDescription\n"; 

                array_push($jsonArray,
                    array(
                        "type" => $type, 
                        "shortType" => $shortType,
                        "name" => $name, 
                        "shortName" => $shortName, 
                        "description" => $description, 
                        "shortDescription" => $shortDescription, 
                        "image" => $image,
                        "id" => $id,
                        "success" => true
                        )
                    );

            }

        } else {

                array_push($jsonArray, array(
                        "type" => "default", 
                        "shortType" => "default",
                        "name" => "default", 
                        "shortName" => "default", 
                        "description" => "default", 
                        "shortDescription" => "default", 
                        "image" => "default",
                        "id" => "default", 
                        "success" => false
                    )
                ); 
        }

        //echo "well data";

        echo json_encode(array("Items" => $jsonArray)); 

    }  catch(Exception $e){
        die($e->getMessage());
    }
}

然后我如何调用我的函数:

getFeaturedCrops();

这是我的数据库屏幕截图enter image description here

0 个答案:

没有答案