Question

My Php code is

<?php
include('session.php');
include('db.php');

$session=$_SESSION['agent'];

$home1 = "SELECT fullname FROM users WHERE role='$session'";
$result1=mysql_query($home1) or die(mysql_error());
while ($row1=mysql_fetch_array($result1)) {

echo $gallery = "'".$row1[0]."',"; // output is 'sam','teja','multiplevaluessoon',


$home = "SELECT * FROM chat WHERE chat.from IN ('$gallery')";
}
$result=mysql_query($home) or die(mysql_error());

while ($row=mysql_fetch_array($result)) {

    $msg         =$row["message"];
    echo $randomUserId=$row["from"];
   echo $msg . "<br/>";
   }
 ?>

here $gallery contains ',' comma at the end, so i am getting a error in where clause, when i am trying to trim the output of $gallery

 'sam','teja','multiplevaluessoon',

last charcter inside loop i am getting

 'sam''teja''multiplevaluessoon'

which is trimming all the commas due to while loop, i need last comma to be trimmed so that i can execute it in where clause

please suggest me any ideas

Was it helpful?

Solution

Make use of rtrim().

$yourfinaltext = rtrim($yourcommadelimitedstring, ',');

Change your while like this.

while ($row1=mysql_fetch_array($result1)) {

      $gallery .= "'".$row1[0]."',";
      $home = "SELECT * FROM chat WHERE chat.from IN ('$gallery')";
}
echo rtrim($gallery,',');

OTHER TIPS

$rest = substr("abcdef", 0, -1);  // returns "abcde"

http://php.net/manual/en/function.substr.php

Remove comma as this...

$gallery=substr_replace($gallery ,'',0,1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top