我有一个带有2个coloumns(名字和姓氏)的mysql表,我希望当我运行(select * from names)查询存储到自动增量变量中的所有值,如name1 = john name2 = george等。姓氏相同 surname1 = williams surname2 =詹姆斯。我写了这个,但我不能让它工作
<?php
$name="";
$surname="";
$i =1;
$getinfo = "select * from names ";
$query = mysql_query($getinfo);
while ($row = mysql_fetch_array($query)) {
$name.$i. = $row['firstname'];
$surname.$i = $row['lastname'];
}
$i ++;
?>
答案 0 :(得分:0)
这是可能的,但这是一件非常奇怪的事情:
while ($row = mysql_fetch_array($query)) {
++$i;
$nameKey='name'.$i;
$surnameKey='name'.$i;
$$nameKey = $row['firstname'];
$$surnameKey = $row['lastname'];
}
相反,为什么不简单地使用数字数组呢?
while ($row = mysql_fetch_array($query)) {
$name[] = $row['firstname'];
$surname[] = $row['lastname'];
}
或者,更优雅:
while ($row = mysql_fetch_array($query)) {
$persons[] = [
'name' => $row['firstname'],
'surname' => $row['lastname']
];
}
答案 1 :(得分:0)
要实现您的目标,您需要使用以下语法:
$i = 1;
while ($row = mysql_fetch_array($query)) {
${'name'.$i} = $row['firstname'];
${'surname'.$i} = $row['lastname'];
$i++;
}
但这不是一个干净的方法。我建议你使用如下的数组:
while ($row = mysql_fetch_array($query)) {
$names[] = $row['firstname'];
$surnames[] = $row['lastname'];
}