Chủ Nhật, 9 tháng 5, 2010

PHP: Insert Data Into MySQL Table Using An Array

Inserts the values of an array into a table. Also supports specifying if a specific field needs to be encoded using PASSWORD()
Parameters:
Table: Name of table to insert into
Data: array of $field->$value of new data
Password Field: Which field in the data array needs to be surrounded with PASSWORD() (optional)

function mysql_insert_array($table, $data, $password_field = "") {
foreach ($data as $field=>$value) {
$fields[] = '`' . $field . '`';
if ($field == $password_field) {
$values[] = "PASSWORD('" . mysql_real_escape_string($value) . "')";
} else {
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
}
$field_list = join(',', $fields);
$value_list = join(', ', $values);
$query = "INSERT INTO `" . $table . "` (" . $field_list . ") VALUES (" . $value_list . ")";
return $query;
}

Không có nhận xét nào: