如何使用函数从数据库中进行选择并将值存储在数组中?
我想从表中进行选择,获取所有值并将它们放入数组中,返回函数,然后在另一个文件中调用它,然后在调用另一个函数并向其提供数组值时循环遍历数组。谢谢
<?php
function getusers()
{
//db parameters here
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
$query = "SELECT user_name FROM userinfo";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
return $final[] = $row['user_name'];
}
mysql_Close ($conn);
}
?>
getusers() 返回一个数组,我在另一个文件中调用它
include('usernames.php');
getusers();
while!(end of [$final] array)
{
getTax($final[]);
}
function getTax($final)
{
//statement here
}
I want to select from a table, get all the values and put them in an array, return the function, and call it in another file, and loop through the array whiles i call another function and supply it with the array values. Thanks
<?php
function getusers()
{
//db parameters here
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
$query = "SELECT user_name FROM userinfo";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
return $final[] = $row['user_name'];
}
mysql_Close ($conn);
}
?>
getusers() returns an array and I call it in another file
include('usernames.php');
getusers();
while!(end of [$final] array)
{
getTax($final[]);
}
function getTax($final)
{
//statement here
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
并在其他文件中:
And in other file:
目前您的
getusers()
函数不正确您可以调整您的
getusers()
函数以返回用户数组,如下所示:然后在另一个文件中,您可以包含此内容:
Currently your
getusers()
function is incorrectYou could adjust your
getusers()
function to return an array of your users like so:And then in another file, you can include this:
首先,我觉得有必要说您应该使用 PDO,特别是因为
PDOStatement::fetchAll
可以完成您想要的大部分操作。 本教程看起来相对不错。这里有一些重写,但它会做你想做的一切:
在第二个文件中:
First I feel compelled to say that you should be using PDO, especially since
PDOStatement::fetchAll
does most of what you want. This tutorial looks relatively decent.Here's a bit of a re-write, but it will do everything you want it to:
In the second file: