Jackymamouth
Jackymamouth

Reputation: 149

While function in echo

I have some php code that looks like :

echo"
<tr>
<td colspan=\"2\">" . get_comment(${'imgmodp_data_' . $i}['primid']) . "</td>
</tr>
 ";

My get_comment function:

function get_comment($primid)
{
    $dbCon = mysqli_connect("localhost", "something", "something", "something");
    $sql = "SELECT `id_sheep`, `text` FROM `comments` WHERE `primid`='$primid'";
    $query = mysqli_query($dbCon, $sql);

    while($row = mysqli_fetch_array($query))
    {
        return = "<div>" . $row['text'] . "</div></br>";
    }
}

But this only returns one row each time even if they is multiple rows. If I use echo instead of return it returns all lines but at the top of my document, not in the blocks where it should be...

Any suggestions?

Upvotes: 0

Views: 27

Answers (2)

Abdulla Nilam
Abdulla Nilam

Reputation: 38584

What about this

echo "<div>" . $row['text'] . "</div></br>";

and place the php code where you want it to show.

<div class="row">
    <div class="col-sm-12">
        <div class="col-sm-6">
            <!-- PHP code goes here -->
        </div>
    </div>
</div>

Upvotes: 0

Blaatpraat
Blaatpraat

Reputation: 2839

Use a variable before your loop, which you update inside your loop and return after your loop.

If you just use return, you'll stop the function, so after 1 loop.
With echo you output the string directly, but don't stop the loop.

For example:

function get_comment($primid){
$dbCon = mysqli_connect("localhost", "something", "something", "something");
$sql = "SELECT `id_sheep`, `text` FROM `comments` WHERE `primid`='$primid'";
$query = mysqli_query($dbCon, $sql);
$return = '';
while($row = mysqli_fetch_array($query)){
    $return .= "<div>" . $row['text'] . "</div></br>";
}
return $return;
}

Upvotes: 2

Related Questions