Reply to Re: retrieving multiple rows advice

Your name:

Reply:


Posted by Zoe Blade on 11/22/05 09:38

On Tue, 21 Nov 2005, julian_m wrote:

> let's say I've an array of articles's id
>
> $arr_art_id=(1, 551, 2015, 6 .......n )
>
> what option is better (1 or 2), in order to achieve better performance?
>
> (pseudo code)
> 1)
> for i=0 to array count{
> select * from articles where articles.id=$arr_art_id[i]
> mysqlquery($sql)
> //do whatever i have to do
> }
>
>
> 2)
>
> $or ='';
> for i=0 to array count{
> $sql.= $or . 'articles.id='. $arr_art_id[i];
> $or ='or';
> }
>
> $sql = 'select * from articles where' .$sql
>
> mysqlquery($sql)
> //do whatever i have to do
>
> tia
>
> regards - julian maisano

Please for give me, regulars, if I'm out of line or out of my league for a
first post, but I thought I'd help out a bit now that I write PHP for a
living. (Whether I'm any good at it is another story, but at least I've
improved.)

If it's better performance your'e after, Julian, try something like this:

$sql = "SELECT title, body, author FROM articles ORDER BY date ASC";
mysqlquery($sql);
$results = mysql_num_rows($sql);
for ($i=0; $i < $results; $i++)
{
$rows .= mysql_fetch_array($sql);
}

foreach($rows as $row)
{
// Do things
}

Selecting only the columns you want in your SQL statement saves a little
bit of overhead, and you might as well get the database to put them in the
order you want them in. Then you put each row into an array, so it becomes
a two-dimensional array that looks just like the results table.

Then you can use the handy foreach loop to do whatever you want with the
output, one line at a time, without having to do any more queries.

My code is probably slightly off as it's been a while since I've written
procedural PHP code (my boss made me switch to object oriented, which has
sped us up when it comes to writing the projects but is probably slower at
executing the actual code, although not noticably so). But I'd recommend
naming columns, making a two-dimensional array, and using foreach on it,
for what it's worth.

Oh, and making sure you don't use a function as the middle argument in a
"for" loop helps. While it's less code, the line "for ($i=0; $i <
mysql_num_rows($sql); $i++)" would make PHP call up that function every
time it executed the code in the loop.

Does that help?

Zoe.

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация