PDO,MySQL的 - 如何从函数返回一个数组? [英] PDO, MySQL - How do I return an array from a function?

查看:869
本文介绍了PDO,MySQL的 - 如何从函数返回一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个函数来获取从MySQL数据库中多行。我使用foreach循环通过每场比赛。我希望能够每行的ID添加到一个数组,并返回数组回调用程序,然后使用该ID的。

I am using a function to retrieve multiple rows from a mysql database. I use a foreach to loop through each match. I want to be able add the id of each row to an array and return the array back to the calling program to then use the id's.

这是据我试图让,我在正确的方向前进?

This is as far as I have tried to get, am I going in the correct direction?

$resultarray = array();
    $resultarray[] = get_post_data($post_id);

    print_r($resultarray);

code函数:

code in function:

$stmt = $dbh->prepare("SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = ?");
        $stmt->bindParam(1,$post_id);
        $stmt->execute();

        $resultarray = array();
        foreach($stmt as $row):


                $resultarray[] = $img_id = $row['img_id'];


        endforeach;
        return $resultarray;

感谢

推荐答案

如果你只需要在 img_id 字段,你为什么运行 SELECT *

If you just need the img_id field, why are you running select *?

$stmt = $dbh->prepare("SELECT img_id FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = ?");
$stmt->bindParam(1,$post_id);
$stmt->execute();

return $stmt->fetchAll();

另外,您可以通过手动的结果环路(验证/改变返回数组语法)有:

Alternatively you could loop through the results manually (to validate/change the return array syntax) with:

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    //code
}

这篇关于PDO,MySQL的 - 如何从函数返回一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆