 |
สอบถามเรื่องการวนลูป insert ข้อมูล ด้วยวิธีกาเขียนด้วย oop ค่ะ |
|
 |
|
|
 |
 |
|
สอบถามวิธีการวนลูป เมื่อรับข้อมูลมาเป็น arrayอะค่ะ
ตอนนี้ที่ทำได้ เปนการ insert ข้อมูลที่รับเข้ามาแค่ครั้งเดียว ถ้าต้องการให้เป็น array ควรจะแทรกโค๊ด เข้าไปตรงส่วนไหนอะค่ะ
Code (PHP)
public function insert($table,$fireld_name,$values)
{
$this->insert=mysql_query("insert into {$table} ($fireld_name) values ($values)");
if(!$this->insert){echo mysql_error();}//ฟ้องตรงนี้ว่า No database selected }
}
ตอนใส่ค่า
Code (PHP)
$db->insert("user","user_id,username,password,nameuser,type_user","'4','yam','1234','yam','2'");
Tag : PHP, MySQL
|
ประวัติการแก้ไข 2012-03-08 11:46:36
|
 |
 |
 |
 |
Date :
2012-03-08 11:44:16 |
By :
kwangz_07 |
View :
1303 |
Reply :
3 |
|
 |
 |
 |
 |
|
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ใช้ foreach ครับ
|
 |
 |
 |
 |
Date :
2012-03-08 12:48:08 |
By :
Dragons_first |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ตามนั้นครับ แทรก function ใน loop ส่ง parameter ให้กับ function ก็ได้แล้วครับ
|
 |
 |
 |
 |
Date :
2012-03-08 15:31:33 |
By :
webmaster |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
แบบนี้เลยครับ
Code (PHP)
public function insertArray($table, $data) {
if (!is_array($data)) { // เช็คให้แน่ใจว่า $data คือ array ถ้าไม่ ก็ออกจากฟังก์ชั่น
return;
}
$columnNames = array();
$values = array();
foreach ($data as $key => $value) { // $data คือ array ที่มี key เป็นชื่อ column และมี value เป็น value ของ column
$columnNames[] = '`' . $key . '`';
$values[] = mysql_real_escape_string($value); // escape มันก่อน เพื่อป้องกัน sql injection
}
mysql_query(
'INSERT INTO `' . $table . '` (' . implode(',', $columnNames) . ') VALUES (' . implode(',', $values) . ')'
);
}
เวลาเรียกใช้ก็ส่ง associative array เข้าไปเป็น input เลยครับ
Code (PHP)
$db->insertArray(array(
'user_id' => '4',
'username' => 'yam',
'password' => '1234',
'nameuser' => 'yam',
'type_user' => '2'
));
|
ประวัติการแก้ไข 2012-03-08 17:43:35 2012-03-08 17:44:06
 |
 |
 |
 |
Date :
2012-03-08 17:42:22 |
By :
actioncookie |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|