使用用户从数据库创建PHP数组

时间:2017-03-04 10:41:20

标签: php sql arrays username

我想创建像这样的$user["1"]数组,如何从数据库中创建它?

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { } 

$sql = "SELECT * FROM Account";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $id = $row["id"];
        $user[$id] = $row["username"];
    }
}
$conn->close();

2 个答案:

答案 0 :(得分:0)

请尝试这样,在插入之前创建一个空数组$user

$user = array();

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $id = $row["id"];
        $user[$i] = $row["username"];
    }
}

答案 1 :(得分:0)

我修好了,我不得不添加更改:

$user[$id] = $row["username"];

于:

$user["$id"] = $row["username"];