你不能。該函數僅返回第一個結果。並沒有更多的信息。
所以你需要返回不同的東西,例如,結果資源:
function get_user_wants($user_id)
{
$query = mysql_query("select product_id from user_wishlist where user_id= $user_id");
return $query;
}
然後,您可以通過它遍歷:
$result = get_user_wants($user_id);
while ($out = mysql_fetch_assoc($result))
{
print_r($out):
}
一種更好的方式則是包裝的結果在迭代器:
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):
}
這樣的結果迭代器可能看起來像:
/**
* 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);
}
}
使用PDO代替,然後您可以輕鬆地迭代結果。此外,你的功能缺少數據庫連接,因此它不適用於多個連接。 – hakre
不推薦使用mysql *系列函數。改爲使用[PDO](http://php.net/manual/en/intro.pdo.php)。 – nico
您應該使用PDO或mysqli。 mysqli擴展名與舊的mysql擴展名幾乎相同。請閱讀PHP文檔中的[選擇API](http://www.php.net/manual/en/mysqlinfo.api.choosing.php)。 –