Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql_field_name to the new mysqli

Tags:

php

mysqli

I have a way to get the name of the columns of a table. It works fine but now I want to update to the new mysqli ? (I tried the mysqli_fetch_field but I don't know how to apply to this case and I am not sure if it is the wright option)

How to do the same with 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;
like image 292
Nrc Avatar asked Jan 31 '13 15:01

Nrc


4 Answers

This is the way to implement this missing function:

function mysqli_field_name($result, $field_offset)
{
    $properties = mysqli_fetch_field_direct($result, $field_offset);
    return is_object($properties) ? $properties->name : null;
}
like image 50
José Carlos PHP Avatar answered Dec 15 '22 01:12

José Carlos PHP


I'm not sure if there is a better way to do that, but I checked that this works to get just the name of the columns and is the new mysqli :

$result = mysqli_query($con, 'SELECT * FROM myTable');
while ($property = mysqli_fetch_field($result)) {
    echo $property->name;
}
like image 33
Nrc Avatar answered Dec 15 '22 00:12

Nrc


You can replace the function mysql_field_name to mysqli_fetch_field_directand use it like the following:

$colObj = mysqli_fetch_field_direct($result,$i);                            
$col = $colObj->name;
echo "<br/>Coluna: ".$col;
like image 34
user3187518 Avatar answered Dec 14 '22 23:12

user3187518


This is another easy way to print each field's name, table, and max length

$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);
}
like image 21
A.A Noman Avatar answered Dec 14 '22 23:12

A.A Noman