mysql 判断字段为主键,如何使用mysqli判断列是否为主键?

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;

}

}

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值