Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Implode problem

Status
Not open for further replies.

franwpd

Programmer
Joined
Jul 8, 2004
Messages
1
Location
US
Here is my DB:

CREATE TABLE `tablenames` (
`tablename_id` int(5) unsigned NOT NULL auto_increment,
`tablename` varchar(25) NOT NULL default '',
PRIMARY KEY (`tablename_id`)
) TYPE=MyISAM AUTO_INCREMENT=3 ;

When I get the DB filled, it should print like this:

A101, A102, A103

With the comma's added but none on the end.

but what I get is

1, A1012, A100

What am I doing wrong?

<php>

$sql = mysql_query("SELECT * FROM tablenames") or die (mysql_error());

$count = mysql_num_rows($sql);

for($i=0;$i<$count;$i++)

{

$row = mysql_fetch_row($sql);
$array = ($row);

$row = implode(", ", $array);
print $row;

}

</php>


 
first of all implode used like that will echo something like
1, A101
2, A102
because it will implode on the rows of the resultset.

second, use echo instead of print.

to get a concatenated stringof tablenames, you must create an array and add elements (the table name) to it from inside the for statement, then use implode on that string.
 
why not just use:

$row = mysql_fetch_array($sql);

instead of

$row = mysql_fetch_row($sql);
$array = ($row);
$row = implode(", ", $array);

Also, because you SELECT * from ...

you will be returning :

tablename_id,tablename
tablename_id,tablename
tablename_id,tablename
....

It seems, that you want :
SELECT tablename from tablenames;

therefore :
Code:
$sql = mysql_query("SELECT * FROM tablenames") or die (mysql_error()); 

$count = mysql_num_rows($sql); 

$i=0;

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

	echo "$row[0]";

	if($i<$count){

		echo ",";
	
	$i++;

	}
}

}

{

$row = mysql_fetch_row($sql);
$array = ($row);

$row = implode(", ", $array);
print $row;

}

[/code]

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Ignore the code not in the code window.

Where's the edit button .. only been asking like for 4 years lol.

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
You can also make KarveR's code a little tighter ...
Code:
$sql = mysql_query("SELECT * FROM tablenames") or die (mysql_error());
if (isset($tmp_array)) unset($tmp_array); 
while($row=mysql_fetch_array($sql))
    $tmp_array[] = $row[0];
echo implode(", ",$tmp_array[]);

Ken Robinson
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top