หัวข้อ : เทคนิคการ insert/update ข้อมูล กรณีมีฟิล์ดเยอะ
ผู้เขียน : ธวัชศักดิ์ แตงเอี่ยม
วันเวลา : 2011-10-05 08:37:05
เปิดอ่าน : 141 *แท็ก : kohana
สำหรับเทคนิคนี้ใช้กับ Kohana เวอร์ชั่น 3 ครับ โดยปกติแล้วเวลาจะ เพิ่มข้อมูลโดยใช้ ORM เราจะเขียนประมาณโค๊ดข้างล่างนี้
public function action_register() {
if ($_POST) {
$customer = ORM::factory('customer')ว
$customer->username = 'tawatsak';
$customer->password = md5($this->request->post('password'));
$customer->save();
$this->request->redirect();
}
}
แต่ในกรณีที่เกิดว่ามีฟิล์ดสัก 10 ฟิล์ด เราจะมานั่งเขียน $customer->fieldname = 'value' ก็เยอะอยู่เหมือนกัน บทความนี้เลยเสนอเทคนิคใหม่ โดยเราสามารถเขียนโดย
public function action_register() {
if ($_POST) {
$customer = ORM::factory('customer')
// เพิ่มตัวแปร post ทั้งหมดไว้ใน Array
->values($_POST, array('username', 'name', 'email', 'phone', 'address'));
// เข้ารหัส "รหัสผ่าน" ก่อนบันทึกลงฐานข้อมูล
$customer->password = md5($this->request->post('password'));
$customer->save();
$this->request->redirect();
}
}
ผลลัพธ์
เพิ่มข้อมูล/แก้ไขข้อมูล ที่ฟิล์ด username, password, name, email, phone and address
เราไม่จำเป็นต้องเขียนแบบ
$customer->username = $this->request->post('username');
หวังว่าคงช่วยลดปริมาณโค๊ดลงเยอะเลยกรณีที่มี ฟิล์ด เกิน 10

ชื่อ :
วิเชียร นุตภูมิ
อีเมล์ :
winuta0059@gmail.com
วันเวลา :
2011-10-26 07:48:58
IP :
0.0.0.0
ผมใช้ kohana v.2 ครับ kohana v.3 ไม่รู้วิธีลงครับ
ชื่อ :
ธวัชศักดิ์ แตงเอี่ยม
อีเมล์ :
admin@thaimind.com
วันเวลา :
2011-10-27 12:47:09
IP :
0.0.0.0
ลองลงดูครับ ถ้าติดปัญหาอะไร โพสลงกระดานสนทนาเลยนะครับ
บทความ PHP