我有这段代码来调用数据库中的帖子
<?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
它运行正常,但我想创建一个包含查询和while循环的函数并将其移动到functions.php并将html代码保存在template.php中,但我不知道如何使用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
}
我试过这个,但没有结果
答案 0 :(得分: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']);
答案 1 :(得分: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