Jump to content

last comma removal in loop


87dave87

Recommended Posts

I have the following code which displays all of the tables in my database with a comma in between each, e.g. "table1, table2, " the problem is that the last comma needs to be removed, I have looked into this and have been told about rtrim or implode functions, although ive tried both in my code with no joy, the following is my code using rtrim which still displays the last comma...

 

<?php

include($_SERVER['DOCUMENT_ROOT'] . '/includes/dbconnect.php');

$query = mysql_query('show tables');

$result = $query or die(mysql_error());

 

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

echo $row[0],", ";

$row[0] = rtrim( $row[0],", ");

}

?>

Link to comment
https://forums.phpfreaks.com/topic/38505-last-comma-removal-in-loop/
Share on other sites

I always find it easier to put everything I want to eventually be in a comma separated list into a temporary array then implode the array using a comma as the delimiter:

<?php
nclude($_SERVER['DOCUMENT_ROOT'] . '/includes/dbconnect.php');
$tmp = array();
$query = mysql_query('show tables');    
$result = $query or die(mysql_error());

while($row = mysql_fetch_array($result)){
   $tmp[] = $row[0];
}

$csl = implode(',',$tmp);
echo $csl;
?>

 

Ken

thanks! this maybe the wrong place to ask but does anyone have any idea on how i could implement that code into the following code where the from ".$query1."  part is? im trying to do this to search all tables in my database: -

 

<?

include($_SERVER['DOCUMENT_ROOT'] . '/includes/head.php');

include($_SERVER['DOCUMENT_ROOT'] . '/includes/dbconnect.php');

$query1 = mysql_query('show tables');

$search_query = "select emulator, version, os, platform, details from ".$query1." where emulator LIKE '%".mysql_real_escape_string($_POST["emusearch"])."%' OR platform LIKE '%".mysql_real_escape_string($_POST["emusearch"])."%' order by platform asc, emulator asc";

 

if (empty($_POST['emusearch']))

{

echo "<meta http-equiv='refresh' content='0; URL=/noresults.php'>";

exit();

}

else

{

$search = mysql_query($search_query);

$num_rows = mysql_num_rows($search);

 

if($num_rows < 1)

{

  echo "<meta http-equiv='refresh' content='0; URL=/noresults.php'>";

exit();

}

}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.