如何使用PHP中的bind_params正确地将数据提取到数组

时间:2015-11-28 16:52:42

标签: php mysql fetch

我目前正在尝试执行一些MySQL查询并使用bind_params将结果保存到数组中,用于2个参数:userUniqueId (String)limit (used to LIMIT query records)。我试图自己做,但似乎代码不能正常工作。我尝试过不同的方法,但仍然没有。你能帮我吗?查询工作正常,因为我已经在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);
?>

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您可以使用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指定要返回的最大行数。

enter image description here

因此,您获得此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);