Jump to content

MySQL Fetch Array


Cypher_489

Recommended Posts

Hi,

Just a simple question.

[code] $sql = mysql_query("SELECT * FROM dt_directories WHERE category = '$category'") or die(mysql_error());
 
while ( $dirs = mysql_fetch_array($sql) ) {
$name = $dirs['name'];
echo "$name, ";
}[/code]

This echos out the names of directories which are from the category stored in the variable $category like this (category is "general"): Dmoz, Yahoo, Best of the Web, and so on...

What I want to do is, rather then echo it, is to store them in a variable with the formatting like in the example.

TIA
Link to comment
https://forums.phpfreaks.com/topic/13379-mysql-fetch-array/
Share on other sites

Yes you can do that. Just git rid of the echo statement. But the $name variable can [b]only[/b] be used on the page it was created on. It cannot be used on another page. So if you want to use $name over multiple pages you might want to store it in a session/cookie.
Link to comment
https://forums.phpfreaks.com/topic/13379-mysql-fetch-array/#findComment-51656
Share on other sites

Also you would need to set it like this to make the variable hold all the values comma seperated


$sql = mysql_query("SELECT * FROM dt_directories WHERE category = '$category'") or die(mysql_error());
 
while ( $dirs = mysql_fetch_array($sql) ) {
$name = $name."$dirs[name], ";
}

to make name 1 list like it echo's if i'm right in how i interprited what you wnat?


Regards
Liam
Link to comment
https://forums.phpfreaks.com/topic/13379-mysql-fetch-array/#findComment-51660
Share on other sites

Just one more thing on this topic, I've found the last element in the array:

$last_sql = mysql_query("SELECT * FROM dt_directories WHERE category = '$category' ORDER BY name DESC LIMIT 1") or die(mysql_error());

while ( $last = mysql_fetch_object($last_sql) ) {
$last_element = "$last->name";
}

How will I incorporate this into the $name variable so that the last element doesn't have the comma after it.

I've tried a simple
if( $name != $last_element) {
$name = $name."$dirs[name], ";
else {
$name = $name."$dirs[name]"; }

but that doesn't work, any ideas?
Link to comment
https://forums.phpfreaks.com/topic/13379-mysql-fetch-array/#findComment-51682
Share on other sites

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.