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;
}
}