如何在 PHP 中使用 bind_params 正確獲取數據到數組 (How to correctly fetch data to array with bind_params in PHP)


問題描述

如何在 PHP 中使用 bind_params 正確獲取數據到數組 (How to correctly fetch data to array with bind_params in PHP)

我目前正在嘗試執行一些 MySQL 查詢並使用 bind_params 將結果保存到一個數組中以獲得 2 個參數:userUniqueId (String)limit(用於限制查詢記錄)</代碼>。我試圖自己做某事,但似乎代碼無法正常工作。我嘗試了不同的方法來做到這一點,但仍然沒有。你能幫我嗎?查詢工作正常,因為我已經在 phpMyAdmin 中對其進行了測試我要編寫的函數必須將記錄提取到數組中,然後我想 json_encode 該數組使用該數組作為函數的結果。

這是我的功能代碼:

public function getUserFavouriteRecipes($user_unique_id, $limit) {
    $stmt = $this‑>conn‑>prepare("SELECT recipe.`unique_id`, recipe.`title`, recipe.`img_tumbnail_link`, recipe.`add_date`, recipe.`kitchen_type`, recipe.`meal_type`, user.`name`, user.`surname`, 
                                    (SELECT count(*) from `like` WHERE recipe.`unique_id` = `like`.`recipe_unique_id_fk`) AS like_count 
                                    FROM `recipe` 
                                    JOIN `favourite` ON (recipe.`unique_id` = `favourite`.`recipe_unique_id_fk`) 
                                    JOIN `user` ON (recipe.`user_unique_id_fk` = user.`unique_id`) 
                                    WHERE favourite.`user_unique_id_fk` = ?
                                    ORDER BY recipe.`add_date` DESC
                                    LIMIT ?, 10");
    $converted_limit = intval($limit);                      

    $stmt‑>bind_param("si", $user_unique_id, $limit);   
    $result = $stmt‑>execute();

    if ($result) {
        $myArray = array();

        // Fetching Rows From Query
        while ($row = $result‑>get_result()‑>fetch()) {
            $myArray[] = $row;
        }
        $stmt‑>close();

        return $myArray;
    } else {
        return NULL;
    }
}

我在這裡嘗試對其進行編碼:

<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// Receiving The Post Params
$user_unique_id = $_POST['user_unique_id_fk'];
$limit = $_POST['limit'];

// Getting Result Array
$resultArray = $db‑>getUserFavouriteRecipes($user_unique_id, $limit);
echo json_encode($resultArray);
?>

提前感謝您的幫助。


參考解法

方法 1:

The correct way to fetch results using prepared statements is:

...    
$stmt‑>execute();
$myArr = array();
$tmp = array();
$stmt‑>bind_result($tmp['unique_id'], $tmp['title'], ...); // all fields in select
$i = 0;
while($stmt‑>fetch()) {
    $myArr[$i] = $tmp;
    $i++;
}
if (count($myArr) > 0) {
    return $myArr;
} else {
    return false;
}

方法 2:

You can use PDOStatement::fetchAll() to return an array containing all of the result set rows, like this:

public function getUserFavouriteRecipes($user_unique_id, $limit) {

    // your code

    $stmt‑>execute();
    return $stmt‑>fetchall(PDO::FETCH_ASSOC);
}

$resultArray = $db‑>getUserFavouriteRecipes($user_unique_id, $limit);

To encode the results you can do:

$json=json_encode($resultArray);

And if you want to display the results, you can do something like this:

//loop over the $resultArray, setting $result to an array representing each row
foreach($resultArray as $result){
    //loop over each $result (row), setting $key to the column name and $value to the value in the column.
    foreach($result as $key=>$value){
        //echo the key and value.
        echo "{$key} = {$value}<br>";
    }
}

Edited:

public function getUserFavouriteRecipes($user_unique_id, $limit) {

    // your code

    $status = $stmt‑>execute();

    $myArray = array();
    if($status){
        // Extract result set and loop rows
        $result_set = $stmt‑>get_result();

        while($result = $result_set‑>fetch_assoc()){
            $myArray[] = $result;
        }
        return $myArray;
    }else{
        return NULL;
    }

}

$resultArray = $db‑>getUserFavouriteRecipes($user_unique_id, $limit);
$json = json_encode($resultArray);

Your issue lies here:

The following illustrates the LIMIT clause syntax with two arguments:

SELECT 
    column1,column2,...
FROM
    table
LIMIT offset , count;

Let’s examine the LIMIT clause parameters:

  • The offset specifies the offset of the first row to return. The offset of the first row is 0, not 1.
  • The count specifies maximum number of rows to return.

enter image description here

So the reason you're getting this string '[]' (length=2) result is because of the fact that it's not able to fetch any record based on your offset and count.

Try this:

public function getUserFavouriteRecipes($user_unique_id, $limit) {
    $stmt = $this‑>conn‑>prepare("SELECT recipe.`unique_id`, recipe.`title`, recipe.`img_tumbnail_link`, recipe.`add_date`, recipe.`kitchen_type`, recipe.`meal_type`, user.`name`, user.`surname`, 
                                    (SELECT count(*) from `like` WHERE recipe.`unique_id` = `like`.`recipe_unique_id_fk`) AS like_count 
                                    FROM `recipe` 
                                    JOIN `favourite` ON (recipe.`unique_id` = `favourite`.`recipe_unique_id_fk`) 
                                    JOIN `user` ON (recipe.`user_unique_id_fk` = user.`unique_id`) 
                                    WHERE favourite.`user_unique_id_fk` = ?
                                    ORDER BY recipe.`add_date` DESC
                                    LIMIT ?");
    $converted_limit = intval($limit);                      

    $stmt‑>bind_param("si", $user_unique_id, $converted_limit);   

    $status = $stmt‑>execute();

    $myArray = array();
    if($status){
        // Extract result set and loop rows
        $result_set = $stmt‑>get_result();

        while($result = $result_set‑>fetch_assoc()){
            $myArray[] = $result;
        }
        return $myArray;
    }else{
        return NULL;
    }
}

$resultArray = $db‑>getUserFavouriteRecipes($user_unique_id, $limit);
$json = json_encode($resultArray);
//var_dump($json);

(by anton86993ondrejbaRajdeep Paul)

參考文件

  1. How to correctly fetch data to array with bind_params in PHP (CC BY‑SA 2.5/3.0/4.0)

#fetch #MySQL #PHP






相關問題

mysql fetch 中的 $row 是什麼類型的變量? (What kind of variable is $row from a mysql fetch?)

如何在 PHP 中使用 bind_params 正確獲取數據到數組 (How to correctly fetch data to array with bind_params in PHP)

使用 JavaMail 加速電子郵件檢索 (Speed up email retrieval with JavaMail)

使用 eclipselink 從多個表中獲取數據 (Fetch data from multiple tables using eclipselink)

如何在 Webassembly 中獲取 JSON 文件 (How to Fetch a JSON file in Webassembly)

mysqli(a,b,c,d)->query(sql)->fetch_assoc() 究竟是如何工作的? (How exactly does mysqli(a,b,c,d)->query(sql)->fetch_assoc() work?)

如何在 .map 中返回異步函數? (How do I make an asynchronous function return in .map?)

如何僅在響應中的 onclick 事件後映射 json 列表? (How to map a json list only after an onclick event in react?)

在第二個 API 中使用來自第一個 API 的信息 - React (Using information from the first API in the second one - React)

使用 Jest 測試框架調用 fetch(url) 時如何根據 url 模擬變量響應? (How to mock variable responses based on the url when fetch(url) is called using the Jest testing framework?)

函數不返回對像以供 .then 使用 - 但能夠 console.log 對象,並明確返回它 (Function not returning object for .then to work with - but able to console.log the object, and am explicitly returning it)

fetch api - 400 加載資源失敗 (fetch api - 400 failed to load resource)







留言討論