2015-10-20 77 views
0

我有一個主鍵列其數據,包含ID所以它必須是唯一的PHP和MySQL:查詢是否存在,並創建如果不存在

的內容是這樣的

enter image description here

ID

格式<index>/<division>/<month in roman>/<last 2 digit of year>

我的問題是,什麼是最好的QUER y以檢查是否ID已經存在, 與<index>+1/<division>/<month in roman>/<last 2 digit of year>

這是我的函數生成的ID

public function gen_id($id_type = "HL.BY") { 
    $id_num = 123; 
    $month = $this->romanic_number(date("n")); 
    $year = substr(date("Y"),-2); 
    $index_number = sprintf("%04d", $id_num); 

    $id = $index_number . "/" . $id_type . "/" . $month . "/" . $year; 
    return $id; 
} 

如果我的問題不明確創建ID請詢問

+0

插入如果不存在http://stackoverflow.com/questions/1361340/how-to-insert-if-not-exists-in-mysql –

+0

爲什麼不讓id自動遞增?您的其他數據應該放在單獨的列中,這將很難在路上使用這些數據。 – chris85

+0

@ chris85你的意思是自動遞增index_number?,不幸的是我需要使用以前的程序員數據庫 – stacheldraht27

回答

0

如果你需要使用現有的數據庫,你可以確保這樣的唯一ID ...

1)兩個字段創建一個表...

$createSQL1 = $conn->prepare("CREATE TABLE IF NOT EXISTS `nxtnum` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `nxtnum` int(11) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1"); 

$createSQL1->execute(); 

$insertSQL1 = $conn->prepare("INSERT INTO `nxtnum` (`id`, `nxtnum`) VALUES (1, 501)"); 

$insertSQL1->execute(); 

其中,「501」是所有現有ID的最高第一部分加1

2)獲取的數量爲這行代碼的... $id_num = 123; ...

$sql = "SELECT * FROM nxtnum"; 
$query = $conn->prepare($sql); 
$query->execute(); 
$row = $query->fetch(PDO::FETCH_ASSOC); 

其中$conn是你的數據庫連接文件

3)創建新的唯一ID ...

public function gen_id($id_type = "HL.BY") { 
$id_num = $row['nxtnum']; // this is the new incremented number (incremented in step 4) 
$month = $this->romanic_number(date("n")); 
$year = substr(date("Y"),-2); 
$index_number = sprintf("%04d", $id_num); 

$id = $index_number . "/" . $id_type . "/" . $month . "/" . $year; 
return $id; 
} 

4)增量的櫃檯......

$num = $row['nxtnum'] + 1; 
$sql = "UPDATE nxtnum SET nxtnum=:num"; 
$stmt = $conn->prepare($sql); 
$stmt->bindValue(':num', $num, PDO::PARAM_INT); 
$stmt->execute(); 

現在你所有的設置下一個ID和你的ID將永遠是獨一無二的

編碼快樂!

注意:當然,第一步只需要做一次。

相關問題