以下代码运行正常。但是我想用循环输出结果。我可以通过单独遍历每个键或以$ post [0]为例进行,但不使用循环来遍历所有返回的字段。我得到的只是“数组”的一个值。看起来整个数组都插入到一个变量中我不知道发生了什么。我试过了http://www.hackingwithphp.com/5/3/0/the-two-ways-of-iterating-through-arrays。任何建议表示赞赏,如果有人能解释发生了什么,那将是很好的。谢谢。
$ID = $_POST['ID'];
function query($ID){
$servername = "x.x.x.x";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM GROUP WHERE ID = '$ID'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
$resArr[] = $row;
}
return $resArr;
}
$person = query($ID);
foreach($person as $post) {
echo $post['ID'] . "<br>";
echo $post['NAME'] . "<br>";
echo $post['POSITION'] . "<br>";
echo $post['TELEPHONE_NUMBER'] . "<br>";
echo $post['EMAIL'] . "<br>";
}
?>
答案 0 :(得分:2)
它并不完全清楚你在问什么,但我想你想要遍历所选行的各个字段。当您构建一个包含查询结果的数组时,每个结果本身都是一个数组mysqli_fetch_array($result)
,那么您只需添加一个内部循环来处理单个行数组,如下所示: -
$persons = query($ID);
foreach($persons as $person) {
foreach ( $person as $fieldname => $value ) {
echo $fieldname . '-' . $value . "<br>";
}
}
答案 1 :(得分:0)
Group
是mysql的保留字,你可以在backtics``
$query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM `GROUP` WHERE ID = '$ID'";
$result = mysqli_query($conn, $sql);