我正在编写一个 PHP 脚本连接到数据库获取数组中的所有订单。($结果)我想遍历数组并获取所有“userName”问题是,通过下面的代码,我只能获取数组中每个“userName”的第一个字符。我想要一个包含所有“userName”的数组。<?php$dbhost = 'localhost';$dbuser = 'user';$dbpass = 'password';$dbname = 'dbname';//Create database connection$dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);$sql = "select * from ordertest";$retval = mysqli_query($dblink, $sql) or die(mysqli_error($dblink));$result = mysqli_fetch_array($retval, MYSQLI_ASSOC);if (mysqli_num_rows($retval) > 0) { $arr = json_decode($result, true); foreach ($result as $key => $value) { echo $value["userName"]; }} else { echo $sql;}
1 回答
慕运维8079593
TA贡献1876条经验 获得超5个赞
解决方案应该是:
<?php
$sql = "select * from ordertest";
// retrieve query result from DB
$retval = mysqli_query($dblink, $sql) or die(mysqli_error($dblink));
// if result not empty
if (mysqli_num_rows($retval) > 0) {
// retrieve single row from $retval
while ($result = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo $result["userName"];
echo "\n";
}
} else {
echo $sql;
}
- 1 回答
- 0 关注
- 97 浏览
添加回答
举报
0/150
提交
取消