Php printing data from database

I am trying to get the data from the database, but there is a problem printing it out

function getData($connection)
    {
        $query = "SELECT Email FROM SUBSCRIPTIONS";
        $result = $connection->query($query);
        return $result->fetch_all();
    }

$rows = $databaseOperations->getData($connection);
var_dump($rows);
foreach($rows as $row){
    echo('Data: ' . $row . "<br>");
}

And I am getting:

array(2) { [0]=> array(1) { [0]=> string(12) "sfddsffdsfsd" } [1]=> array(1) { [0]=> string(13) "fdsdffsdsfddf" } }
Warning: Array to string conversion in C:UsersRaitisDocuments\admin.php on line 47
Data: Array

Warning: Array to string conversion in C:UsersRaitisDocuments\admin.php on line 47
Data: Array

So, data is in the $rows, but as result, I get an array? String is essentially array of chars, but PHP shouldn’t treat string as an array of chars, because printing it out would be hell.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

As the data is output as such:

[
    [[string]]
    [[string]]
]

You could try the following:

foreach($rows as $row){
    echo('Data: ' . $row[0] . "<br>");
}

Method 2

You cannot echo an Array! each $row inside $rows might or still represent an array

you can:

foreach($rows as $row){
    echo "nData: n";
    print_r($row);
    echo "<br>";
}

or:

foreach($rows as $row){
    echo('Data: ' . $row[0] . "<br>");
}

depending on the arrays built and response.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x