开发者

PHP 2 Functions Display Results

I want two functions. First function stores 开发者_如何学Goinfo, while the second one displays the info. How would I get the second function to display all that is stored in $info_id and $info_title?

 function get_info()
 {
   $dbc = get_dbc();
   $info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));
   while ($info_row = mysqli_fetch_array($info))
   {
     $info_id = $info_row['info_id'];
     $info_title = $info_row['info_title'];
   }
 }


You can split that function into two using the following approach:

function get_info()
{
  $result = array();

  $dbc = get_dbc();
  $info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));

  while ($info_row = mysqli_fetch_array($info))
  {
    $result[] = $info_row;
  }

  mysqli_free_result($info); // it is good practice to free the result yourself
  return $result;
}

function display_info(array $result)
{
  foreach ($result as $info_row) {
    echo 'id: ' . $info_row['info_id'] . "\n";
    echo 'title: ' . $info_row['info_title'] . "\n";
  }
}

You then can call the functions the following way:

$info = get_info();
// do stuff
display_info($info);


If you want to store it, append the fetched arrays to an array:

function get_info() {
    $dbc = get_dbc();
    $info = mysqli_query($dbc, "SELECT info_id, info_title FROM text") or die("Error: ".mysqli_error($dbc));
    $results = array();
    while ($info_row = mysqli_fetch_array($info)) {
        $results[] = $info_row;
    }
    return $results;
}

Or if you want to view the data, you can print_r the array.

print_r(get_info());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜