繁体   English   中英

如何在PHP中使用bind_params正确获取数据到数组

[英]How to correctly fetch data to array with bind_params in PHP

我目前正在尝试执行一些MySQL查询,并使用bind_params的2个参数将结果保存到数组中: userUniqueId (String)limit (used to LIMIT query records) 我尝试自己做某事,但是代码似乎无法正常工作。 我尝试了不同的方法来做到这一点,但还是没有。 你能帮我吗? 查询工作正常,因为我已经在phpMyAdmin中对其进行了测试。我要编写的函数必须将记录提取到array中,然后由于该函数,我想使用该数组对数组进行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);
?>

在此先感谢您的帮助。

使用准备好的语句获取结果的正确方法是:

...    
$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;
}

您可以使用PDOStatement::fetchAll()返回包含所有结果集行的数组,如下所示:

public function getUserFavouriteRecipes($user_unique_id, $limit) {

    // your code

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

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

要对结果进行编码,您可以执行以下操作:

$json=json_encode($resultArray);

如果要显示结果,可以执行以下操作:

//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>";
    }
}

编辑:

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);

您的问题在这里:

下面说明了带有两个参数的LIMIT子句语法:

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

让我们检查LIMIT子句参数:

  • offset指定要返回的第一行的偏移量。 第一行的offset是0,而不是1。
  • count指定要返回的最大行数。

在此处输入图片说明

因此,得到此string '[]' (length=2)结果的原因是因为它无法基于offsetcount来获取任何记录。

尝试这个:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM