Jedes Mal, wenn ein Benutzer eine Transaktion öffnet, frage ich die letzte maximale Ziffer in seiner Transaktion plus 1 ab.
Aber manchmal stellte ich fest, dass das Ergebnis die maximale ID einer anderen Benutzertransaktion zurückgab. Angeblich hat Benutzer A die letzte ID = 5402 und Benutzer Z hat die letzte ID = 19201. Manchmal erhält Benutzer A die 19202 statt 5403.
Das ist meine Abfrage:
Code: Select all
SELECT MAX(CAST(id AS UNSIGNED)) as max_id FROM `transaction` WHERE `user_id` = 'A'
id INT PK
user_id INT
... etc
Dies ist eine Webanwendung und mehrere Benutzer verbinden sich gleichzeitig und ich verwende MySQL als Datenbank und PHP als Programmiersprache.
Ich verwende CI, hier ist der Code, den ich verwende, um die maximale ID zu erhalten
Code: Select all
function get_max($table, $max_col, $col_id = NULL, $id = NULL) {
if (!empty($col_id) && !empty($id)) {
$this->db->where($col_id, $id);
}
$this->db->select("MAX(CAST($max_col AS UNSIGNED)) as max_$max_col");
$query = $this->db->get($table);
if ($query->num_rows() > 0) {
return intval($query->row_array()["max_$max_col"]);
}
return 0;
}
Code: Select all
$new_data['id'] = $this->model_share->get_max('transaction', 'id', 'user_id', $user_id) + 1;
$new_data['user_id'] = $user_id;
$this->model_share->insert('transaction', $new_data); // save data
Code: Select all
function insert($table, $data) {
$this->db->insert($table, $data);
$id = $this->db->insert_id();
if ($id db->affected_rows() > 0;
else return $id;
}
Mobile version