php SQL 查询结果为字符串(或变量)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1228382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL query result in a string (or variable)
提问by
Is it possible to output SQL query result in one string or variable? (i'm bad in php and mysql) Let's say I have db "agents" with columns - agent_id, agent_fname, agent_lname, agent_dept.
是否可以将 SQL 查询结果输出为一个字符串或变量?(我在 php 和 mysql 方面很差)假设我有一个带有列的数据库“代理”——agent_id、agent_fname、agent_lname、agent_dept。
Using this query:
使用此查询:
$sql = SELECT a.`agent_fname` FROM agents a WHERE a.`agent_dept` = 'FCA'
I want to get a string or a variable, so I can use it in any place of my php file (i.e. $my_variable which outputs the result of my query). Is it possible? If yes - how?
我想得到一个字符串或一个变量,所以我可以在我的 php 文件的任何地方使用它(即输出我的查询结果的 $my_variable)。是否可以?如果是 - 如何?
Thank you!
谢谢!
*I have more than one row.
*我不止一排。
回答by Dirk
I'm assuming you are doing something like:
我假设你正在做这样的事情:
$result = mysqli_query ($link, $sql).
The 'i' in mysqli is for 'improved' which is what you should be using these days.
mysqli 中的“i”用于“改进”,这是您现在应该使用的。
This $result is not your output yet. You must call:
这个 $result 还不是你的输出。您必须致电:
while ($row = mysqli_fetch_assoc($result)) {
print_r ($row);
}
The above code gives you $row, which is your actual output, in the form of an array.
上面的代码以数组的形式为您提供 $row,这是您的实际输出。
回答by Dominic Rodger
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("Name: %s", $row['agent_fname'],);
}
回答by Lance Rushing
If you want to pass around a single variable representing your records. You couldbuild a two dimensional array. like:
如果你想传递一个代表你的记录的变量。您可以构建一个二维数组。喜欢:
$records = array();
$mysqli_result = mysqli_query ($link, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$records[] = $row;
}
This will give you an array variable, $records, will all of your results. Which is easy to pass around. (maybe as an arg to another function.) HOWEVER, this is a pattern that can eat up a lot of memory.
这将为您提供一个数组变量 $records,将显示您的所有结果。这很容易传递。(也许作为另一个函数的参数。) 但是,这是一种会占用大量内存的模式。
It is much better to pass around the $mysqli_result.
传递 $mysqli_result 会好得多。

