2016-01-24 31 views
2

我想要得到最後一個查詢插入id.but我的代碼總是返回零。Mysqli最後一個插入ID不工作

我的代碼

private function Cnn() 
{ 
    return mysqli_connect('localhost','root','root','db'); 
} 
protected function MyCommandInsertId($sql) 
{ 
    if(mysqli_query($this->Cnn(),$sql)) 
    { 
     return mysqli_insert_id($this->Cnn()); 
    } 
    $this->err = mysqli_error($this->Cnn()); 
    return false; 
} 

public function Insert() 
{ 

     $sql = "insert general_info(name,email,password) 
     values('".$this->ms($this->name)."','".$this->ms($this->email)."','".md5($this->password)."')"; 
     //print''.$sql.''; 

     $last_insert_id=$this->MyCommandInsertId($sql); 

} 

回到這裏mysqli_insert_id($this->Cnn());總是返回零

+0

mysqli_insert_id()函數返回查詢在具有AUTO_INCREMENT屬性的列的表上生成的ID。如果最後一個查詢不是INSERT或UPDATE語句,或者如果修改後的表沒有包含AUTO_INCREMENT屬性的列,則此函數將返回零。 [PHP手冊](http://php.net/manual/en/mysqli.insert-id。php) – silverfox

+0

列有AUTO_INCREMENT屬性@silverfox – Twer1971

+0

檢查是否有插入表中的新記錄? – user3422161

回答

1

請檢查mysqli_insert_id的定義: -

的mysqli_insert_id()函數返回最後一個查詢使用的ID(與AUTO_INCREMENT產生的)。

這意味着您的表中有任意一列有AUTO_INCREMENT的值不存在。

或者

無數據插入你的表中CURREN程序流編程發生。由於在代碼中沒有插入查詢,所以它返回

注意: - 只要在代碼中先插入查詢,然後檢查mysqli_insert_id給出的輸出是什麼。然後,你可以很容易地理解什麼我試圖say.Thanks

我的地方工作的示例是在這裏: -

<?php 
error_reporting(E_ALL); 
ini_set('display_errors',1); 
function Cnn() 
{ 
    $conn = mysqli_connect('localhost','root','','stack'); 
    return $conn; 
} 
function MyCommandInsertId($sql) 
{ 
    $conn = Cnn(); 
    if(mysqli_query($conn,$sql)) 
    { 
     $lastid = mysqli_insert_id($conn); 
     return $lastid; 
    }else{ 
     $err = mysqli_error($conn); 
     return $err; 
    } 

} 
function Insert() 
{ 
     $sql = "INSERT INTO bom(bom_description,product_id,finish_product,bom_quantity,UOM) values('Table cleaner','','','','')"; 
     $st_insert_id = MyCommandInsertId($sql); 

     echo $st_insert_id; 

} 
Insert(); 
?> 

輸出: - http://prntscr.com/9u2iyv(插入ID)和插入後http://prntscr.com/9u2j6i(table視圖)

+0

插入命令更新問題 – Twer1971

+0

@ Twer1971感謝您進行標記。很高興幫助你。 –

1

根據 http://php.net/manual/en/mysqli.insert-id.php

有2個可能的問題

  1. 連接
  2. 0123上沒有以前的查詢
  3. 查詢沒有更新AUTO_INCREMENT值

解決方案:

  1. 檢查有插在你的桌子
  2. 檢查你的領域是AUTO_INCREMENT與否的新紀錄。

通過CBroe,你是做一個新的連接。 所以,它認爲你沒有插入新的記錄。


重寫函數Cnn()並將其更改爲私有變量。

+0

是插入記錄,id列是AUTO_INCREMENT屬性 – Twer1971