long executation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
m2babaey
Forum Contributor
Posts: 364
Joined: Sun May 20, 2007 9:26 am

long executation

Post by m2babaey »

Hi
what is ther problem of this code:

Code: Select all

<?php
include'global.php';
$result=mysql_query("SELECT * FROM articles ORDER BY id LIMIT 20");
$row = mysql_fetch_array($result);
while($row){

echo $title=$row['title'],$name=$row['name'];
}
?>
It brings a long result after a long time ( so long that IE cannot browse it and I have to use firefox)
in addition, the result is not what I need. I need the title of 20 last post articles
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

please try

Code: Select all

require 'global.php';

$query = 'SELECT Count(*) FROM articles';
$result = mysql_query($query) or die(mysql_error());
echo 'count: ', mysql_result($result, 0), "<br />\n";
$query = "EXPLAIN SELECT * FROM articles ORDER BY id LIMIT 20";
$result = mysql_query($query) or die(mysql_error());
while( false!==($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
  foreach($row as $k=>$v) {
    echo $k,'=', $v, '; ';
  }
  echo "<br />\n";
}
and post the output.
m2babaey
Forum Contributor
Posts: 364
Joined: Sun May 20, 2007 9:26 am

Post by m2babaey »

this is the output:
count: 68
id=1; select_type=SIMPLE; table=articles; type=index; possible_keys=; key=PRIMARY; key_len=4; ref=; rows=68; Extra=;
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Because there is only one mysql_fetch_array before the while loop the script is fetching only the first record and processes it again and again and again ...

Code: Select all

<?php
include'global.php';
$result=mysql_query("SELECT * FROM articles ORDER BY id LIMIT 20");

while( false!==($row=mysql_fetch_array($result)) ) {
  echo 'title=', $row['title'], 'name=', $row['name'], "<br />\n";;
}
?>
You should also set an index for id, see http://www.w3schools.com/sql/sql_create.asp
But for 68 records it's not that important.
m2babaey
Forum Contributor
Posts: 364
Joined: Sun May 20, 2007 9:26 am

Post by m2babaey »

id is a primary key. is that enough?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

oops, yes that's enough.
I only saw the possible_keys=;
but not key=PRIMARY;
Post Reply