Page 1 of 1

[PHP & MySQL]My code isn't efficient

Posted: Thu Jul 27, 2006 12:19 pm
by Locust

Code: Select all

$cols = 0;

while($row = mysql_fetch_array($result)){
$cols++;
}

while($row = mysql_fetch_array($result)){
echo ("<a href=\"".$row['men_url']."\">".$row['men_value']."</a>");

if ($cols > 1) {echo " | ";}
$cols--;
}
This is my code so that when it's done I have something like

URL 1 | URL 2 | URL 3 | URL 4 | URL 5

As you can see it seperates each URL with a '|' but I have 2 "while" statements in my code which I believe could potentially slow things down. I'm a bit of a perfectionist and I think this code could be better placed. Anyone have any ideas to cut this down?

Posted: Thu Jul 27, 2006 12:23 pm
by tecktalkcm0391
what is the first while doing?

and i think this would work better:

Code: Select all

$cols = 0; 

while($row = mysql_fetch_array($result)){ 
$cols = $cols+1; 
} 

while($row = mysql_fetch_array($result)){ 
echo ("<a href=\"".$row['men_url']."\">".$row['men_value']."</a>"); 

if ($cols > 1) {echo " | ";} 
$cols = $cols-1; 
}

Posted: Thu Jul 27, 2006 12:25 pm
by Locust
The first 'while' is simply counting the number of results from the database query. Then every time a fetch is made, it returns the result and subtracts '1' from $cols.

I want it to sepperate each URL with a | and this is the only way I can think of doing it but I don't think it's optimised.

Posted: Thu Jul 27, 2006 12:30 pm
by feyd
mysql_num_rows()

alternately, you could simply add each record to an array the use a slightly clever implode()

Posted: Thu Jul 27, 2006 12:34 pm
by Locust
I like mysql_num_rows()

For anyone else that's interested, my end code:

Code: Select all

$result = mysql_query($query);

$num_rows = mysql_num_rows($result);

while($row = mysql_fetch_array($result)){
echo ("<a href=\"".$row['men_url']."\">".$row['men_value']."</a>");

if ($num_rows > 1) {echo " | ";}
$num_rows--;
}
Thanks as always Feyd

Posted: Thu Jul 27, 2006 12:37 pm
by daedalus__
There are faster fetchers than _array, aren't there?

Posted: Thu Jul 27, 2006 7:42 pm
by Locust
If you have another suggestion to my code I'm all ears :D

Posted: Thu Jul 27, 2006 7:49 pm
by Benjamin
Here ya go..

Code: Select all

$result = mysql_query($query);

while($row = mysql_fetch_assoc($result)) {
    $records[] = '<a href="' . $row['men_url'] . '">' . $row['men_value'] . '</a>';
}

echo implode(' | ', $records);

Posted: Thu Jul 27, 2006 7:54 pm
by Benjamin
feyd wrote:alternately, you could simply add each record to an array the use a slightly clever implode()
I didn't even see that when I wrote my code :roll:

Posted: Fri Jul 28, 2006 1:12 am
by daedalus__
i thought that mysql_fetch_row was the fastest way to gather data from a resource but i could be wrong.