简体   繁体   English

MYSQL PHP:如何找到总数。 行中的列数?

[英]MYSQL PHP: How can i find total no. of columns in a Row?

$result = mysql_query("select * from formtable") or die("Records could not be fetched");
    while($row=mysql_fetch_row($result))  
    { 
           echo $row[0].$row[1].$row[2];
    }

The above code runs perfect. 上面的代码运行完美。 But i find this statement -> echo $row[0].$row[1].$row[2] bit too static. 但是我发现这条语句-> echo $row[0].$row[1].$row[2]太静态了。 Because if a new column is added i will have to modify the code as echo $row[0].$row[1].$row[2].$row[3] . 因为如果添加了新列,我将不得不将代码修改为echo $row[0].$row[1].$row[2].$row[3]

So, How can i count total columns of the row in order to avoid such a problem? 因此,如何计算行的总列数以避免此类问题?

You can use count($row) to find the number of fields. 您可以使用count($ row)查找字段数。 But it is better to use a foreach loop as previously suggested. 但是最好使用前面建议的foreach循环。

Better to use something like:- 最好使用以下内容:

foreach($row AS $column)
{
echo $column;
}

mysql_num_fields() is what you're looking for. mysql_num_fields()是您要寻找的。

Just to not leave it unspoken; 只是为了不让它说出来; the mysql_* family functions are deprecated, for new code you should use mysqli or PDO . 不推荐使用mysql_*系列函数,对于新代码,应使用mysqliPDO

Wouldn't it make more sense to use something like this: 使用这样的东西不是更有意义:

echo implode($row);

No need to use a loop when there's a function that does it for you... 当有一个函数可以为您完成循环时,无需使用循环...

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

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