2012-12-30 2 views
0

SQL 쿼리를 기반으로 일부 행을 배열로 가져 오는 함수가 있습니다. 해당 배열은 함수에서 반환됩니다. 반환 된 배열의 모든 요소를 ​​어떻게 트래버스 할 수 있습니까? 나는 PHP로 초보자입니다.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); 

그것은 단지 첫 번째 요소, 또는 첫 번째 레코드를 인쇄!

+0

대신 PDO를 사용하면 결과를 쉽게 반복 할 수 있습니다. 또한 함수는 데이터베이스 연결이 누락되어 다중 연결에서 작동하지 않습니다. – hakre

+0

mysql * 계열의 함수는 더 이상 사용되지 않습니다. 대신 [PDO] (http://php.net/manual/en/intro.pdo.php)를 사용하십시오. – nico

+0

PDO 또는 mysqli를 사용해야합니다. mysqli 확장은 이전 mysql 확장과 거의 같다. PHP 문서에서 [Choose API] (http://www.php.net/manual/en/mysqlinfo.api.choosing.php)를 읽어보십시오. –

답변

1

는 출발점으로

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

을보십시오. 이 같은

+2

당신에게 아무 것도주지 않을 것입니다 print_r 이미하지 않았습니다 –

+0

예제는 mysql_fetch_assoc에 의해 주어진 첫 번째 열의 열을 반복 할 것입니다. 그 이유는 가져온 행에 해당하는 연관 배열을 반환하고 내부 데이터 포인터를 앞쪽으로 이동시키기 때문입니다. 한 번에 단 하나의 알입니다. –

+0

예, print_r은 이미하지 않았습니다. 그러나 이것이 요점입니다 : "print_r()"블랙 박스를 보는 방법으로 OQ를 읽습니다. 대부분의 경우, 당신은 단지 내용을 에코합니다. 이 해석은 틀릴 수도 있습니다 ... 어떤 경우에 OQ에 대한 편집은 괜찮을까요? –

4

시도 뭔가 :

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

그리고 당신은 이미 그것을 발견하지 않은 경우

가, 누군가가 MySQLI 또는 PDO 같은 다른 것 대신 MySQL을 사용에 대해 불꽃됩니다. 그들이 당신을 괴롭히지 않게하십시오. 여기서 중요한 점은 쿼리가 잠재적으로 많은 행을 반환하므로 스크립트에서 처리 할 수 ​​있도록 모든 행을 검색하기 위해 일종의 반복자가 필요하다는 것입니다.

이 경우, 각 $ row 배열에는 하나의 product_id 요소가 있습니다. print_r() 함수의 출력을 보면 코드를 어떻게 바꿀 수 있는지 분명히 알 수 있습니다. 이것은 당신이 원하는 것일 수도 있습니다 (제 생각 엔).

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; 
} 
+0

while() iterator에서 불균형 한 괄호 인 구문 분석 오류를 자유롭게 해결하십시오. –

+0

감사합니다, stackoverflow 사람들이 아주 좋은 웹 dev에 있습니다 :) – Faizan

+0

사실 나는 지금 일하고있어, 기본적으로 나는 함수 밖에서받은 배열을 조작 싶었어요. 어쨌든 이제 끝났어. – Faizan

2

당신은 그래서 당신은 오직 첫 번째 행을 얻을 것이다 mysql_fetch_assoc() 단일 호출의 결과를 반환한다. 그들에

루프 다차원 배열을 만들려면 다음 반환 :는 mysql_* 라이브러리가 지원되지 않습니다 :

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

가 사이드 참고 :

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

을 이제 foreach와 루프를 할 수 MySQLi 또는 PDO로 업그레이드하는 것이 좋습니다.

+0

각각 또는 while 루프에 어떤 차이가 있습니까? – Faizan

+0

while을 사용하여 행을 가져 오면 표준 php 배열이있을 때 for each 루프를 사용할 수 있습니다. – MrCode

2

수 없습니다. 이 함수는 첫 번째 결과 만 반환합니다. 그리고 더 이상의 정보는 없습니다. 그런 다음 그 위에 반복 할 수

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); 
    } 
} 
+0

고마워, 나는 보통 가장 간단한 해결책을 찾으러 간다. 나는 이것이 내가 원한 것이라고 생각한다. – Faizan

+0

@Faizan : 정말 간단한 해결책을 보려면 여기를 계속 읽으십시오. http://stackoverflow.com/a/11580420/367456 - PDO도 살펴보십시오. 그것은 당신의 인생을 더 쉽게 만들 것입니다. – hakre

관련 문제