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
JavaScript
x
Notice: Array to string conversion in C:xampphtdocspokus_phpmyadmin_getphp_code_jen_seznam.php on line 16
Array,
Notice: Array to string conversion in C:xampphtdocspokus_phpmyadmin_getphp_code_jen_seznam.php on line 16
Array,
Notice: Array to string conversion in C:xampphtdocspokus_phpmyadmin_getphp_code_jen_seznam.php on line 16
Array,
data_to_array.php
JavaScript
<?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();
Advertisement
Answer
Try this:
JavaScript
while($row = $result->fetch_assoc()) {
array_push($array1, $row["username"]);
}
You can also make the for loop neater:
JavaScript
foreach($array1 as $item) {
echo $item . ',';
}
In your original code you were inserting an array with the lement ‘username’ to your $array1
Writing just ['foo']
is the same as array('foo');