简体   繁体   中英

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.

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'];
    }

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'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM