mysql_insert_id() Sure จริงเหรอ?
หน้าแรก PHP MySQL เกร็ดความรู้ mysql_insert_id() Sure จริงเหรอ?
เทคนิคเล็กน้อย เกี่ยวกับการอ้างอิง record ในฐานข้อมูล MySQL
PHP ใน module MySQL จะมีคำสั่ง mysql_insert_id()
CODE
int mysql_insert_id ( [resource link_identifier] )
Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
คำสั่ง mysql_insert_id() นี้ จะคืนค่า ของ Key(Auto increment) มาให้ แต่มันไม่ได้รับประกันว่า จะคืน record ที่เราเพิ่งใส่เข้าไปนี่...?? หากมีคน insert ข้อมูลพร้อมกันพอดีล่ะ ต้องเกิดความผิดพลาดแน่...
ลองดูทางแก้ 2 วิธี
1. Lock Table ซะเลย
CODE
mysql_query("LOCK TABLES apc_forms WRITE");
mysql_query("SET AUTOCOMMIT = 0");
mysql_query("INSERT INTO apc_forms (form_title, form_event_id, form_expirey) VALUES ('title',1,'2005-10-10')");
define('ID',mysql_query("SELECT LAST_INSERT_ID()"));
mysql_query("COMMIT");
mysql_query("UNLOCK TABLES");
2.อ้างอิงด้วย unique ID
ใช้จำนวจตัวเลขมั่วๆ ที่ไม่ซ้ำกัน อาจคำนวณจากวันที่ เวลา หรือนำตัวอักษรรวมไปด้วยก็ได้ แล้วเอาไปใส่ไว้ใน field แล้วเอา field นั้นไว้ใช้อ้างอิง ลองดูสัก 4 ตัวอย่าง
CODE
$token = md5(uniqid());
<?PHP
$token = md5(uniqid());
echo $token ."<br>";
$better_token = md5(uniqid(rand(), true));
echo $better_token ."<br>";
$prefix = 'Narisa'; // a universal prefix prefix
$my_random_id = $prefix;
$my_random_id .= chr(rand(65,90));
$my_random_id .= time();
$my_random_id .= uniqid($prefix);
echo $my_random_id ."<br>";
$random_id_length = 10; //set the random id length
$rnd_id = crypt(uniqid(rand(),1)); //generate a random id encrypt it and store it in $rnd_id
$rnd_id = strip_tags(stripslashes($rnd_id)); //to remove any slashes that might have come
$rnd_id = str_replace(".","",$rnd_id); //Removing any . or / and reversing the string
$rnd_id = strrev(str_replace("/","",$rnd_id));
$rnd_id = substr($rnd_id,0,$random_id_length);//finally I take the first 10 characters from the $rnd_id
echo $rnd_id ."<br>";
?>
<?PHP
$token = md5(uniqid());
echo $token ."<br>";
$better_token = md5(uniqid(rand(), true));
echo $better_token ."<br>";
$prefix = 'Narisa'; // a universal prefix prefix
$my_random_id = $prefix;
$my_random_id .= chr(rand(65,90));
$my_random_id .= time();
$my_random_id .= uniqid($prefix);
echo $my_random_id ."<br>";
$random_id_length = 10; //set the random id length
$rnd_id = crypt(uniqid(rand(),1)); //generate a random id encrypt it and store it in $rnd_id
$rnd_id = strip_tags(stripslashes($rnd_id)); //to remove any slashes that might have come
$rnd_id = str_replace(".","",$rnd_id); //Removing any . or / and reversing the string
$rnd_id = strrev(str_replace("/","",$rnd_id));
$rnd_id = substr($rnd_id,0,$random_id_length);//finally I take the first 10 characters from the $rnd_id
echo $rnd_id ."<br>";
?>
ไม่ใช่เทคนิคล้ำลึกอะไร หวังว่าจะมีประโยชน์กับมือใหม่บ้าง...
ขึ้นไปด้านบน
