how to tell if column is primary key using mysqli?

2020-03-01 20:09发布

问题:

I am converting some of my code from the older mysql extension to the mysqli extension in PHP. Previously, with the mysql extension, I had used some code like this to find the primary key in a table:

while ($i < mysql_num_fields($result)) {
    $meta = mysql_fetch_field($result, $i);
    if ($meta->primary_key == 1){ 
        $primary_key = $meta->name; 
    }
    $i++;
}

$meta->primary_key == 1 was very convenient.

So far I have converted to code to using mysqli:

while ($i < $result->field_count) {
    $meta = $result->fetch_field;
    if ($meta->primary_key == 1){ 
        $primary_key = $meta->name; 
    }
    $i++;
}

Of course, from looking at the docs here we can see that $meta->primary_key doesn't exist in mysqli. I see that there is a $meta->flags. This is my best guess, although i am not sure of what value flags should be when I have a primary key.

Does anyone know how I tell which column is the primary key for a table using mysqli?

Thanks!

EDIT Here is some working code:

//get primary key
$primary_key = '';
while ($meta = $result->fetch_field()) {
    if ($meta->flags & MYSQLI_PRI_KEY_FLAG) { 
        $primary_key = $meta->name; 
    }
}

回答1:

You were very close, you will need the flags property.

The flag you are looking for is MYSQLI_PRI_KEY_FLAG, which means:

Field is part of a primary index

You can test for this flag with something like:

if ($meta->flags & MYSQLI_PRI_KEY_FLAG) { 
  //it is a primary key!
}

You are using & here as a Bitwise AND Operator.