Skip to content
Advertisement

How to add elements to a string from $row? [closed]

How I can get this query to create another string from the outputted rows?

You see, ‘$convert’ contains 2 values from my limits table which are 1 and 38, when I echo $convert, I end up with a string which is: “138” Does anyone know how I can convert it to a string which would be: “1, 38”? with a ‘,’ in between each ID. I need it to be like this so I can put it into another query as a condition.

I have tried functions like Implode() and split() but I’m having no luck. Any help would be appreciated. Code below.

$SQL_Ban = "SELECT banned_ItemID FROM limits WHERE UserID = 2;";
$banResult = mysqli_query($connection, $SQL_Ban);
                
if(mysqli_num_rows($banResult) > 1) {
    while($row = mysqli_fetch_array($banResult)) {
    
        $convert = $row['banned_ItemID'];

        var_dump($convert);

OUTPUT: string(1) “1” string(2) “38”

The output shows that they are in two (2) strings, but I need a ‘,’ to be in the middle of them.

Advertisement

Answer

Collect all strings into an array and then merge the array using implode()

$SQL_Ban = "SELECT banned_ItemID FROM limits WHERE UserID = 2;";
$banResult = mysqli_query($connection, $SQL_Ban);
                
if(mysqli_num_rows($banResult) > 1) {
    $strings = []; // empty array
    foreach($banResult as $row) {
        // append into an array
        $strings[] = $row['banned_ItemID'];
    }
    // merge the elements using ', ' as a separator
    echo implode(', ', $strings);
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement