返回与库MySQLi和阵列多行 [英] Returning Multiple Rows with MySqli and Arrays
本文介绍了返回与库MySQLi和阵列多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在过去的两天,所以我一直在我的转换功能的mysqli。我碰到的一个问题。我有返回包含从数据库中的行阵列的功能。不过,我想该数组包含多个行,而不是之一。另外,我怎么就能够呼应出个别职位。这是我失败的尝试,只有数组中显示一行。
$ = mysqli的新的mysqli(本地主机,用户,密码,数据库);功能display_posts($ mysqli的,$ USER_ID){ $栏=`primary_id`,`poster_id`,`profile_user_id`,`POST` $ USER_ID =(INT)$ USER_ID; $查询=SELECT FROM`posts` DISTINCT $领域WHERE`profile_user_id` = $ USER_ID
LIMIT 4; 如果($结果= $ mysqli->查询($查询)){ $行= $ result-> FETCH_ASSOC(); 返回$行; $ result->免费(); $ stmt->关闭();}}
在这里,我想显示的数据。
$ user_ID的= 1;$帖= display_posts($ mysqli的,$ user_ID的);//不知道做什么用$岗位做。 While循环也许是为了显示每个职位?
解决方案
您必须使用一个循环,让他们一次全部:
< PHP
功能resultToArray($结果){
$行=阵列();
而($行= $ result-> FETCH_ASSOC()){
$行[] = $行;
}
返回$行;
}//用法
$查询=SELECT FROM`posts` WHERE`profile_user_id` = $ user_id的LIMIT 4个不同的领域$;
$结果= $ mysqli->查询($查询);
$行= resultToArray($结果);
后续代码var_dump($行); //排阵
$ result->免费();
For the past two days or so I've been converting my functions to mysqli. I've run into a problem. I have a function that returns an array containing a row from the database. However, I want the array to contain multiple rows versus one. Also, how would I be able to echo out the individual posts. Here is my failed attempt that only displays one row in the array.
$mysqli = new mysqli("localhost", "user", "password", "database");
function display_posts ($mysqli, $user_id) {
$fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
$user_id = (int)$user_id;
$query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id
LIMIT 4";
if ($result = $mysqli->query($query)) {
$row = $result->fetch_assoc();
return $row;
$result->free();
$stmt->close();
}}
Here I am trying to display the data.
$user_id = 1;
$posts = display_posts($mysqli, $user_id);
//Not sure what to do with $posts. A While loop perhaps to display each post?
解决方案
You have to use a loop to get them all at once:
<?php
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4';
$result = $mysqli->query($query);
$rows = resultToArray($result);
var_dump($rows); // Array of rows
$result->free();
这篇关于返回与库MySQLi和阵列多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文