开发者

Return a MySQL row in a function as an array

I'm trying to create a function to return all of the users in a database as an array. When I print_r the users, I'm getting a multi-dimensional array returned:

Ex:

Array ( [0] => Array ( [0] => Albers [1] => Abbings [2] => Blaine [3] 

Code:

   <?php
        session_start();
        function getActiveUsers() {
            $con = mysql_connect("-","-","-");
            if (!$con)
              {
              die('Could not connect: ' . mysql_error());
              }
            else {
                // connected to database successfully
            }
            mysql_select_db("casemanagers", $co开发者_如何学Cn);
            $result = mysql_query('select * from users');
            $arr = array();
            while($row= mysql_fetch_assoc($result)){
                $arr[] = $row['Name'];
            }
            return array ($arr);
        }

        $row = array();
        $row = getActiveUsers();
        print_r($row);

    ?>

Can anyone tell me why this is happening or steps I can take to fix it? Thanks.


It's the return line: you should return $arr not array($arr).

What you did there was to create a new array with $arr as its only element.


It's because you do:

return array ($arr);

just do:

return $arr;


Try this:

<?php
    session_start();
    function getActiveUsers() {
        $con = mysql_connect("-","-","-");
        if (!$con)
          {
          die('Could not connect: ' . mysql_error());
          }
        else {
            // connected to database successfully
        }
        mysql_select_db("casemanagers", $con);
        $result = mysql_query('select * from users');
        $arr = array();
        while($row= mysql_fetch_array($result)){ //<-- use array instead of assoc
            $arr[] = $row['Name'];
        }
        return $arr; //<-- just return the array, nothing outside it
    }

    $row = array();
    $row = getActiveUsers();
    print_r($row);

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜