sql >> データベース >  >> RDS >> Mysql

php経由でmysqldbからすべての製品カテゴリを取得してjson配列を返す方法

    PHP側の場合、これは、categories配列を取得してjsonを作成する方法です。プリペアドステートメントの場合、これは、達成できる方法です

    $success = false;
    try {
    
      $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $success = true;
    }
    catch(PDOException $e) {
    $response["success"] = 0;
    $response["message"] = 'Connection failed: ' . $e->getMessage();
    $response["data"]=null;
    die(json_encode($response));
    }
    
    $query_categories = "SELECT category_name FROM categories";
    
    try{
    
    $sth = $sth->prepare($query_categories );
    $success = true;
    
    } catch(PDOException $e) {
    $response["success"] = 0;
    $response["message"] = 'Prepare failed: ' . $e->getMessage();
    $response["data"]=null;
    die(json_encode($response));
    }
    
    try{
    $sth->execute();
    $success = true;
    } catch(PDOException $e) {
    $response["success"] = 0;
    $response["message"] = 'Execute failed: ' . $e->getMessage();
    $response["data"]=null;
    die(json_encode($response));
    }
    
    $categories = $sth->fetchAll(PDO::FETCH_COLUMN, 0);/* fetches all categories from db */
    
    /* Output of $query_categories
    Array
    (
        [0] => cat1
        [1] => cat2
        [2] => cat3
        [3] => cat4
    )
    */
    /* json encode $query_categories 
    ["cat1","cat2","cat3","cat4"]
    */
    
    /* check if categories exist or not*/
    if(empty($categories)){
            $response["success"] = 0;
            $response["message"] = "No categories found";
            $response["data"]=null;
            die(json_encode($response));
            $connection = null; 
    
    }
    
    if($success) {
        $response["success"] = 1;
        $response["message"] = "Kylie";
        $response["data"]=$categories;
        die(json_encode($response));
        $connection = null;      
     /* output
     {"success":0,"message":"Kylie","data":["cat1","cat2","cat3","cat4"]}
     */
    } else {
        $response["success"] = 2;/* don't where you are setting success to 2*/
        $response["message"] = "something went wrong";
        $response["data"]=null;
        die(json_encode($response));
        $connection = null;
    }
    
    } else {
            $response["success"] = 3;/* don't where you are setting success to 3*/
            $response["message"] = "Another brick in the wall";  
            $response["data"]=null; 
            die(json_encode($response));
            $connection = null;
    }
    

    私はJavaが得意ではありませんが、ここにリファレンスJSONを解析してその値を配列に変換する方法

    /* store json string in  the_json */
    JSONObject myjson = new JSONObject(the_json);
    JSONArray the_json_array = myjson.getJSONArray("data");
    

    PHPデータオブジェクト



    1. SQLServerデータベース名の変更

    2. ページネーションページ番号を制限する

    3. 接続プールの問題

    4. mysqlシステムコマンド