php - 如何在PHP中获取mysql列/字段值而不指定每个字段?

标签 php mysql

我是 PHP 和 MySQL 的初学者,所以请耐心等待......

我正在尝试使用for循环获取mysql表的字段值。我知道如何使用 mysql_fetch_array 来获取它,但问题是我必须指定每个字段。我想通过获取字段的数量并使用循环来获取值来完成此操作。我还尝试了 mysql_fetch_field ,但找不到任何返回该值的函数。

这是 mysql_fetch_field 返回值的列表:

  • name - 列名称
  • table - 列所属表的名称
  • max_length - 列的最大长度
  • not_null - 如果列不能为 NULL,则为 1
  • Primary_key - 如果该列是主键,则为 1
  • unique_key - 如果该列是唯一键,则为 1
  • multiple_key - 如果列是非唯一键,则为 1
  • numeric - 如果列是数字则为 1
  • blob - 如果列是 BLOB,则为 1
  • type - 列的类型
  • unsigned - 如果列无符号则为 1
  • Zerofill - 如果列为零填充,则为 1

我也尝试阅读有关 mysql_result 的内容,但似乎您必须指定该字段。

mysql_result [field]

The name or offset of the field being retrieved.

It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.


这是我的代码片段:

<table> 
 <tr>
  <?php
   for ($i = 0; $i < mysql_num_fields($result); ++$i) echo  "<th>" . mysql_field_name($result, $i) . "</th>"  ;
  ?>
 </tr>
 <?php 
  for ($i = 0; $i < mysql_num_rows($result); ++$i) {  
   echo "<tr>";
   for ($j = 0; $j < mysql_num_fields($result); ++$j) {
    echo "<td>" . // this is where I want to put the function . "</td>";
   }
   echo "</tr>";
  }
 ?>
</table>

请帮忙...

最佳答案

我使用我制作的这个函数,它将 SQL 的所有结果返回到一个数组中。

<?php
function getResultRows($result)
{
    $rows = array();
    while ($row = mysql_fetch_array($result)){
        $rows[] = $row;
    }
    return $rows;
}

$sql = 'SELECT * FROM myTable WHERE 1=1';
$result = mysql_query($sql);
$rows = getResultRows($result);
print_r($rows);
?>

array(
    [0]array(
        [0]id => 0
        [1]name => blah
    )
    [1]array(
        [0]id => 5
        [1]name => test
    )
)

关于php - 如何在PHP中获取mysql列/字段值而不指定每个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6247834/

相关文章:

php - Paypal 开发者账号

php - sql 列出带有左连接的游戏和总评论?

mysql - 对特定索引中的最后一条记录求和

PHP fatal error : Class 'Zend\Mvc\Application' not found

php - 如何在使用 PHP 调试在 Visual Code 中调试时设置变量值?

php - Linux 内核 2.6.18-128.1.10.el5 中 grep 的默认绝对路径

sql - 需要从mysql中包含不同类别的唯一id的表中获取数据

php - 将多行插入表中

MySQL:从另一个表的随机行复制多个值

php - 从数据库中加载值以根据上一个下拉菜单中的选择创建下拉菜单