我有下面的代码并且它应该正常工作但是不是将结果回显到屏幕,我需要将结果存储在名为$ var的php变量中。我该怎么做呢?
<?php
$sql = "SELECT id_member FROM smf_members WHERE FIND_IN_SET(24,additional_groups)";
$con = mysql_connect('localhost', 'sqluser', 'sqlpass');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db");
$result = mysql_query($sql, $con);
while ($row = mysql_fetch_array($result)) {
echo $row['id_member'];
}
mysql_close($con);
?>
答案 0 :(得分:4)
根据您想要实现的目标,有几种可能的方法
$var = "";
while ($row = mysql_fetch_array($result)) {
$var .= $row['id_member'] . "\n";
}
$var = array();
while ($row = mysql_fetch_array($result)) {
$var[] = $row['id_member'];
}
答案 1 :(得分:2)
将echo
替换为$var[]
。
这会将每个结果推送到数组的末尾。首先定义变量可能会很好。
$var = array();
while ($row = mysql_fetch_array($result)) {
$var[] = $row['id_member'];
}
答案 2 :(得分:2)
<?php
$sql = "SELECT id_member FROM smf_members WHERE FIND_IN_SET(24,additional_groups)";
$con = mysql_connect('localhost', 'sqluser', 'sqlpass');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db");
$result = mysql_query($sql, $con);
$v = array(); // $v instead of $var, since var is a keyword and may cause troubles
while ($row = mysql_fetch_array($result)) {
array_push($v, $row['id_member']);
// or
//$v[] = $row['id_member'];
}
mysql_close($con);
&GT;
答案 3 :(得分:1)
如果select语句将返回多个结果,则需要将值存储在数组中:
$member_ids = array();
while ($row = mysql_fetch_array($result)) {
$member_ids[] = $row['id_member'];
}
如果select语句将返回单个结果(您可以通过将LIMIT 1
附加到$sql
变量的值来确保。
$row = mysql_fetch_array($result);
$member_id = $row['id_member'];