简体   繁体   English

php mysql 数据仅显示一行带有 foreach 循环

[英]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 数据库中获取时它没有显示所有行,如下所示:

  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??现在它只显示第一行然后停止为什么它不显示所有字段而且我不想使用 while 循环因为任何人都可以解释我的问题吗?

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.现在问题不在于 str_replace 它与循环或数据库,因为数据库行没有增加并且只显示一个数据。

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相反,您必须在循环中使用 fetch 语句获取所有行

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

From PHP mysq_fetch_array documentation :来自PHP mysq_fetch_array文档

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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