Core
Core

Reputation: 335

Foreach loop only outputting one value

I have a foreach loop that should add a row to the table "notifications"

            $infoquery = "SELECT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
            $identifier = mysqli_query($dbc, $infoquery);
            $rows = mysqli_fetch_array($identifier);
            foreach(array_unique($rows) as $row){
            $core->addNotification($row['user_id'], $link, $description);
            }

however it is only adding one value, when it should add two notifications, one for user 1 and one for user 3

Upvotes: 1

Views: 136

Answers (3)

slevy1
slevy1

Reputation: 3832

Alternatively if you have a small result set, you could use that result to get all the data at once and avoid using iteration to fetch the data by using $result->fetch_all according to the manual (see http://php.net/manual/en/mysqli-result.fetch-all.php), as follows:

<?php
$query = "SELECT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
$identifier = mysqli_query( $dbc, $query );

$result = $mysqli->query( $query );
$rows = $result->fetch_all( MYSQLI_ASSOC );
foreach ( $rows as $row ) {
     $core->addNotification( $row['user_id'], $link, $description );
}

Upvotes: 0

Wrikken
Wrikken

Reputation: 70460

Aside from tkausl's correct answer, your other problem is unique visitors: array_unique compares the string values of an the items in the array.

Let's look at this:

var_dump(strval(array("bob")), strval(array("ed")));

Which outputs:

string(5) "Array"
string(5) "Array"

(and a whole load of errors).

So, as their string representation is the same, if you expect an multidimensional array array(array("user"=>"bob"),array("user"=>"ed")), you will remain with only one entry in there. Now, there's a whole lot of ways to work around that in PHP, but your database is better at it, use:

 SELECT DISTINCT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";

(But do look into prepared statements instead of adding raw parameters / query building).

Upvotes: 1

tkausl
tkausl

Reputation: 14269

You are fetching only one single row, it should be like this:

 $infoquery = "SELECT `user_id` FROM reply WHERE `post_id` = '" .$replyid. "'";
 $identifier = mysqli_query($dbc, $infoquery);
 while($row = mysqli_fetch_array($identifier)){
     $core->addNotification($row['user_id'], $link, $description);
 }

Upvotes: 2

Related Questions