php 将mysql字段名添加到新的mysqli

ckx4rj1h  于 2023-02-28  发布在  PHP
关注(0)|答案(5)|浏览(144)

我有一种方法可以获取表中列的名称。它工作正常,但现在我想更新到新的mysqli?(我尝试了mysqli_fetch_field,但我不知道如何应用于这种情况,我不确定它是否是wright选项)
如何对mysqli执行相同的操作?:

$sql = "SELECT * from myTable";
$result = mysql_query($sql,$con);
$id = mysql_field_name($result, 0);
$a = mysql_field_name($result, 1);

echo $id;
echo $a;
icnyk63a

icnyk63a1#

以下是实现此缺失函数的方法:

function mysqli_field_name($result, $field_offset)
{
    $properties = mysqli_fetch_field_direct($result, $field_offset);
    return is_object($properties) ? $properties->name : null;
}
zaq34kh6

zaq34kh62#

我不确定是否有更好的方法来实现这一点,但我检查了一下,这可以只获得列的名称,并且是新的mysqli:

$result = mysqli_query($con, 'SELECT * FROM myTable');
while ($property = mysqli_fetch_field($result)) {
    echo $property->name;
}
rslzwgfq

rslzwgfq3#

可以将函数mysql_field_name替换为mysqli_fetch_field_direct,并按如下方式使用:

$colObj = mysqli_fetch_field_direct($result,$i);                            
$col = $colObj->name;
echo "<br/>Coluna: ".$col;
ego6inou

ego6inou4#

这是打印每个字段的名称、表和最大长度的另一种简单方法

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
{
   // Get field information for all fields
   while ($fieldinfo=mysqli_fetch_field($result))
   {
      printf("Name: %s\n",$fieldinfo->name);
      printf("Table: %s\n",$fieldinfo->table);
      printf("max. Len: %d\n",$fieldinfo->max_length);
   }
   // Free result set
   mysqli_free_result($result);
}
tjjdgumg

tjjdgumg5#

$sql = "SELECT * FROM myTable LIMIT 10";
$ressult = $con->query($sql);
$rows = $result->fetch_all(MYSQLI_ASSOC);
$fields = array_keys($rows[0] ?? []);
echo json_encode($fields);

如果查询未返回行,则可以返回空数组。

相关问题