2

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", $con);
            $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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

It's because you do:

return array ($arr);

just do:

return $arr;

Comments

1

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

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.