如何使用mysqli判断列是否为主键? [英] how to tell if column is primary key using mysqli?
问题描述
我正在将我的一些代码从旧的mysql扩展转换为PHP中的mysqli扩展.以前,通过mysql扩展,我使用了一些类似这样的代码来在表中查找主键:
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
非常方便.
到目前为止,我已经转换为使用mysqli的代码:
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++;
}
当然,通过查看文档此处,我们可以看到$meta->primary_key
在mysqli中不存在.我看到有一个$meta->flags
.这是我的最佳猜测,尽管我不确定拥有主键时flags
的值是多少.
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.
有人知道我如何使用mysqli判断哪一列是表的主键吗?
Does anyone know how I tell which column is the primary key for a table using mysqli?
谢谢!
编辑 这是一些工作代码:
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;
}
}
推荐答案
您非常接近,您将需要flags
属性.
You were very close, you will need the flags
property.
您要查找的标志是 MYSQLI_PRI_KEY_FLAG
,表示:
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!
}
您在此处将&
用作按位AND运算符.
这篇关于如何使用mysqli判断列是否为主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!