2016-06-21 8 views
0

iがデータベースPHPの関数を作成するループ

<?php 
    $q = "SELECT * FROM posts WHERE user_id = '$user_info[id]' ORDER BY id DESC"; 
    $r = mysqli_query($dbc, $q); 

    while($post_info = mysqli_fetch_assoc($r)) { ?> 

// HTML

からの投稿を呼び出すには、このコードを持っていながら、それが正常に動作しますが、私は関数を作成したいとすると、クエリとインクルード...ループはとのfunctions.phpやtemplate.phpにhtmlコードを保つためにそれを移動が、私はどのようにwhileループと分からないながら

function data_post($dbc, $user_info['id']){ 

    $q = "SELECT * FROM posts WHERE user_id = '$user_info[id]' ORDER BY id DESC"; 
    $r = mysqli_query($dbc, $q); 

    while($post_info = mysqli_fetch_assoc($r)) 

    return $post_info 
} 

私はTRいますこれをIEDが、何の結果

+0

しばらく($ post_info = mysqli_fetch_assoc($ rを)){ $ new_array [] = $ post_info; } whileループの外側で$ new_arrayを返します。 – JYoThI

答えて

0
function ss() 
{ 
    ........... 

    while($post_info = mysqli_fetch_assoc($r)) 
    { 
    $new_array[]=$post_info; 

    } 

    return $new_array; 

} 

And return the $new_array outside of the while loop 

And get the value like this 

    $mm= ss(); 

print_r($mm); here you get that $new_array values 
0

はありません、これを試してみてください:

ファンクション本体

function data_post($dbc, $user_id){  
    $q = "SELECT * FROM posts WHERE user_id = '$user_id' ORDER BY id DESC"; 
    $r = mysqli_query($dbc, $q); 

    $arrayPost = array(); 
    while($post_info = mysqli_fetch_assoc($r)){ 
     $arrayPost[] = array('id' => $post_info['postId'], 'name' => $post_info['postName']); 
     // or whatever data you want to return of post, insert in array 
    } 
    return $arrayPost; 
} 

関数呼び出し

$userPostArray = data_post($dbc, $user_info['id']); 
関連する問題