How to print all elements of array returned from a function in Php?

11,628

Solution 1

Try something like this:

$sql = "select product_id from user_wishlist where user_id= $user_id";
$res = mysql_query($sql) or die("FAIL: $sql BECAUSE: " . mysql_error());;
while ($row = mysql_fetch_assoc($res))
{
    print_r($row);
}

And in case you haven't already noticed it, someone will flame you about using MySQL instead of a different thing like MySQLI or PDO. Don't let them bother you. The point here is that your query returns potentially many rows, and you need some kind of iterator to retrieve all of the rows so your script can process them.

In the instant case, there will be one product_id element in each $row array. Once you see the output of the print_r() function, it will probably be obvious how you might change the code. This might turn out to be what you want (I think).

function get_user_wants($user_id)
{
    $sql = "select product_id from user_wishlist where user_id= $user_id";
    $res = mysql_query($sql) or die("FAIL: $sql BECAUSE: " . mysql_error());;
    while ($row = mysql_fetch_assoc($res))
    {
        $out[] = $row['product_id'];
    }
    return $out;
}

Solution 2

You are returning the result of a single call to mysql_fetch_assoc() so you will only ever get the first row.

Loop over them to create a multidimensional array, then return:

function get_user_wants($user_id)
{
    $query=mysql_query("select product_id from user_wishlist where user_id= $user_id");
    $rows = array();
    while($row = mysql_fetch_assoc($query))
    {
         $rows[] = $row;
    }
    return $rows;
}

Now you can loop them with foreach:

$list = get_user_wants(99);
foreach($list as $product)
{
    print_r($product);
}

Side note: the mysql_* library is deprecated, it is recommended to upgrade to MySQLi or PDO.

Solution 3

You can't. The function is only returning the first result. And no more information.

So you need to return something different, for example the result resource:

function get_user_wants($user_id)
{
    $query = mysql_query("select product_id from user_wishlist where user_id= $user_id");

    return $query;
}

You can then iterate over it:

$result = get_user_wants($user_id);

while ($out = mysql_fetch_assoc($result))
{
    print_r($out):
}

A better way then is to wrap the result in an Iterator:

function get_user_wants($user_id)
{
    $query = mysql_query("select product_id from user_wishlist where user_id= $user_id");

    return new MySqlResult($query);
}

$result = get_user_wants($user_id);

foreach ($result as $out)
{
    print_r($out):
}

Such an result iterator could look like:

/**
 * MySql Result Set - Array Based
 */
class MySqlResult implements Iterator, Countable
{
    private $result;
    private $index = 0;
    private $current;

    public function __construct($result)
    {
        $this->result = $result;
    }

    public function fetch($result_type = MYSQL_BOTH)
    {
        $this->current = mysql_fetch_array($this->result, $result_type);
        return $this->current;
    }

    /**
     * Return the current element
     * @link http://php.net/manual/en/iterator.current.php
     * @return array
     */
    public function current()
    {
        return $this->current;
    }

    public function next()
    {
        $this->current && $this->fetch();
    }

    /**
     * Return the key of the current element
     * @link http://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     */
    public function key()
    {
        return $this->current ? $this->index : null;
    }

    /**
     * Checks if current position is valid
     * @link http://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     */
    public function valid()
    {
        return (bool)$this->current;
    }

    /**
     * Rewind the Iterator to the first element
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     */
    public function rewind()
    {
        $this->fetch();
    }

    /**
     * Count of rows.
     *
     * @link http://php.net/manual/en/countable.count.php
     * @return int The count of rows as an integer.
     */
    public function count()
    {
        return mysql_num_rows($this->result);
    }
}

Solution 4

Try

foreach ($out as $key=>$value) 
  echo "$key: $value<br>";

as a starting point.

Share:
11,628
Faizan
Author by

Faizan

A computer science geek ! Portfolio I am a freelancer, web designer and front-end developer. Just say Hi ! www.faizanzahid.me

Updated on June 04, 2022

Comments

  • Faizan
    Faizan almost 2 years

    I have a function that fetches some rows based on the sql query into an array. That array is returned from a function, How can I traverse all the elements of the returned array? I am a beginner in Php.

    function get_user_wants($user_id)
    {
    $query=mysql_query("select product_id from user_wishlist where user_id= $user_id");
    return mysql_fetch_assoc($query);
    }
    
    $out=get_user_wants($user_id);
    print_r($out);
    

    It only prints the first element, or the first record !