0

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();
3
  • 1
    You are not accessing the $row retrieved, use array_push($array1, $row["username"]); Commented Apr 2, 2020 at 19:13
  • Yes, here is what your array currently looks lik 3v4l.org/9fjo7 you need to inspect what you are working with. print_r or var_dump. Commented Apr 2, 2020 at 19:19
  • Thank you @NigelRen and AbraCadaver . Commented Apr 4, 2020 at 13:55

1 Answer 1

1

Try this:

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

You can also make the for loop neater:

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');

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.