PHP INSERT an Array into MySQL
Inserting an array into MySQL while escaping the string with mysql_real_escape_string() will throw up the error:
"mysql_real_escape_string() expects parameter 1 to be string"
I haven't got down to research the real reason behind this issue. The obvious reason is that mysql_real_escape_string() escapes all characters in a string. To escape an array, I guess we'd need to loop the contents and return the escaped array.
The solution:
-- During INSERT or UPDATE
- Serialize the array before the INSERT or UPDATE query
$array_var[] = $some_data;
$serialized_array = serialize($array_var);
// mysql_real_escape_string() will now escape $serialized_array and insert/update without errors.
-- During SELECT
- Unserialize the array after the SELECT query is executed
$array_var = unserialize($get_all[$k]['array_var']);
// Print the array
print_r($array_var);
No comments:
Post a Comment