Keshav Nair
Keshav Nair

Reputation: 423

php mysql data only shows one row with foreach loop

ok i have this and it doesn't show all the rows when fetched from mysql database its like this:

  mysql_select_db($database_config, $config);
    $query_cat = "SELECT * FROM cat";
    $cat = mysql_query($query_cat, $config) or die(mysql_error());
    $row_cat = mysql_fetch_array($cat);

    $arr = array("TIT" => $row_cat['title'],
            "DES" => $row_cat['description']);


    foreach($arr as $ar){
    echo $ar;
    }

now it only displays the first row and then stops why is it not displaying all the fields and i don't wanna use while loop for it can anyone explain me the problem??

EDIT: Well basically i want to work it like this

$p = "{TIT}{DES}";
foreach($arr as $k => $p){
$p = str_replace("{".$k."}", $v, $p);
echo $p;
}

Now the problem is not with str_replace its with the loop or database because the database rows are not incrementing and displays only one data.

Upvotes: 0

Views: 4016

Answers (2)

elitalon
elitalon

Reputation: 9437

From PHP mysq_fetch_array documentation:

"Returns an array that corresponds to the fetched row and moves the internal data pointer ahead"

As far as I know, you cannot retrieve every row without using a loop. You should do something similar to this:

while($row_cat = mysql_fetch_array($cat)){
  echo $row_cat['title'];
  echo $row_cat['description'];
}

Upvotes: 0

Shakti Singh
Shakti Singh

Reputation: 86346

This will always return the first row. you are fetching only once that will return only first row.

Instead you must fetch all the rows using fetch statement in loop

 while($row_cat = mysql_fetch_array($cat)){
       echo $row_cat['title'];
       echo $row_cat['description'];
    }

Upvotes: 4

Related Questions