$sql=" SELECT * from `request_location` where requestid = '".$requestid."' ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
echo "(";
while($row = mysqli_fetch_assoc($result))
{
echo $row["location_tag"];
echo ",";
}
echo ")";
}
I have this above code that displays data in a format where the result is placed within round brackets and each term is separated by a comma
The result that i am getting is like this
(a,b,c,)
Although it seems to be fine but i want that the comma should not appear after c as it is the last term like this
(a,b,c)
Can anyone please tell how to remove comma after the last element
Solution 1:
You can do it using implode() function and array().
Logic behind it:
1) Take a blank array.
2) Fetch the results the same way as existing.
3) Append results to the array.
4) After the loop ends implode()
the array with a comma.
5) Add a prepending and post pending (
and )
to the result.
sql=" SELECT * from `request_location` where requestid = '".$requestid."' ";
$result = mysqli_query($con, $sql);
$arr = array();
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_assoc($result)) {
$arr[] = ["location_tag"];
}
}
echo ! empty($arr) ? '(' . implode(',', $arr) . ')' : '';
Solution 2:
Use MYSQL's GROUP_CONCAT() (if you want to fetch only one field from database table).
sql=" SELECT GROUP_CONCAT(location_tag) from `request_location` where requestid = '".$requestid."' ";
$result = mysqli_query($con, $sql);
$ids = '';
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_assoc($result)) {
$ids = ["location_tag"];
}
}
echo ! empty($ids) ? '(' . $ids . ')' : '';
Try this use PHP str_replace
:-
$str='(a,b,c,)';
str_replace(",)",")",$str);
or try this code :-
$var= "(";
while($row = mysqli_fetch_assoc($result))
{
$var.= $row["location_tag"];
$var.= ",";
}
$var.= ")";
echo str_replace(",)",")",$var);
Use an IF condition and check the num_of_rows
$sql=" SELECT * from `request_location` where requestid = '".$requestid."' ";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
if($count>0)
{
echo "(";
$i = 1;
while($row = mysqli_fetch_assoc($result))
{
echo $row["location_tag"];
if($i<$count) {
echo ",";
}
$i++;
}
echo ")";
}
what about this
$sql= "SELECT * from request_location where requestid = '$requestid'";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
$new = ''
while($row = mysqli_fetch_assoc($result))
{
$new .= $row["location_tag"].",";
}
$data = "(".$new.")"; // Output - (a,b,c,)
$new_data = str_replace(",)", ")", $data);
echo $new_data ; // Output - (a,b,c)
}
For adding "," between two string you can use implode(",", array_variable)
, like below:
$sql=" SELECT * from `request_location` where requestid = '".$requestid."' ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
$location_tag_arr[] = $row["location_tag"];
}
echo ")";
}
echo "(" . implode(",", $location_tag_arr) . ")";
//^output will be: (a,b,c)