【问题标题】:Create PHP array from database with users使用用户从数据库创建 PHP 数组
【发布时间】:2017-03-04 10:41:19
【问题描述】:

我想创建像 $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();

【问题讨论】:

  • 什么不起作用?你有什么错误吗?
  • 为什么要将数字键转换成字符串?我认为没有任何理由这样做。
  • @CasimiretHippolyte 因为我正在制作一个适用于 id 的消息系统。现在我可以在 echo 中使用$user["$from_user"]
  • 您可以对$user[$from_user]$user["$from_user"] 执行相同的操作。 PHP 不是强类型的。

标签: php sql arrays


【解决方案1】:

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

$user = array();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 2011-05-09
    • 2012-01-23
    相关资源
    最近更新 更多