問題描述
我正在將我的一些代碼從舊的 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?
謝謝!
編輯這是一些工作代碼:
//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:
字段是主索引的一部分
您可以使用以下內容測試此標志:
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.
這篇關于如何判斷列是否是使用 mysqli 的主鍵?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!