首页 > 解决方案 > How to append data obtained from database to array?

问题描述

I would like to append data("username") from database to array("array1") and write all items from array. I have marked problematic part of code. If I run this code, I see: What can be wrong?

Output

Notice: Array to string conversion in C:\xampp\htdocs\pokus_phpmyadmin_get\php_code_jen_seznam.php on line 16
Array,
Notice: Array to string conversion in C:\xampp\htdocs\pokus_phpmyadmin_get\php_code_jen_seznam.php on line 16
Array,
Notice: Array to string conversion in C:\xampp\htdocs\pokus_phpmyadmin_get\php_code_jen_seznam.php on line 16
Array, 

data_to_array.php

<?php
$conn = mysqli_connect("localhost", "root", "", "company");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, password FROM login";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // problematic function append from there
    $array1 = array();
    while ($row = $result->fetch_assoc()) {
        array_push($array1, ["username"]);
    }
    for ($x = 0; $x != count($array1); $x++) {
        echo $array1[$x].", ";
    }
    // to there
} else {
    echo "0 results";
}
$conn->close();

标签: phpmysqlarraysmysqli

解决方案


尝试这个:

while($row = $result->fetch_assoc()) {
    array_push($array1, $row["username"]);
}

您还可以使 for 循环更整洁:

foreach($array1 as $item) {
    echo $item . ',';
}

在您的原始代码中,您将一个带有“用户名”的数组插入到您的 $array1中,
写作['foo']方式与array('foo');


推荐阅读