Jump to content

Archived

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

Cypher_489

MySQL Fetch Array

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

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites
I've tried echoing the $name variable outside while() { } before and I only got the last directory in the array.

Share this post


Link to post
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

Share this post


Link to post
Share on other sites
In that case you'll want to make the $name variabled an array which you can do by adding [] at the end of variable name like so:
$name[] = $dirs['name'];

What will happen now $name will store the results as in an array.

Share this post


Link to post
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?

Share this post


Link to post
Share on other sites
NVM, I've fixed it now.

[code]while ( $dirs = mysql_fetch_array($sql) ) {
  $name = $name."$dirs[name], ";
  $names = rtrim($name, ',');
}[/code]

Didn't need the last element info.

Share this post


Link to post
Share on other sites

×

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.