简体   繁体   English

在PHP中创建函数包括while循环

[英]create function in php include while loop

i have this code to call posts from database 我有这段代码可以从数据库中调用帖子

<?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 // html

it works fine but i like to create a function includes the query and the while loop and move it to functions.php and keep the html code in template.php but I don't know how with the while loop.. 它工作正常,但我想创建一个包含查询和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
 }

I have tried this but there is no result 我已经尝试过了,但是没有结果

Try this: 尝试这个:

Function Body 功能体

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

Function Calling 函数调用

$userPostArray = data_post($dbc, $user_info['id']);
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM