I have the following array I want to store in my database...
$insData = array( 'uid' => $fbme['id'], 'first_name' => $fbme['first_name'], 'last_name' => $fbme['last_name'], 'email' => isset($fbme['email']) ? $fbme['email'] : '', 'link' => $fbme['link'], 'affiliations' => $networks, 'birthday' => $info[0]['birthday_date'], 'current_location' => isset($fbme['location']['name']) ? $fbme['location']['name'] : '', 'education_history' => $education, 'work' => $workInfo, 'hometown_location' => isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '', 'interests' => $info[0]['interests'], 'locale' => $info[0]['locale'], 'movies' => $movies, 'music' => $music, 'political' => $info[0]['political'], 'relationship_status' => $info[0]['relationship_status'], 'sex' => isset($fbme['gender']) ? $fbme['gender'] : '', 'tv' => $television, 'status' => '0', 'created' => $now, 'updated' => $now, );
I've tried searching google on how to do this and all I can find is information stating my array needs to be split, before inserting into the table. Is this correct? Sorry for the naivity, very new to php.
You can not insert an array directly to MySQL as MySQL doesn't understand PHP data types. MySQL only understands SQL. So to insert an array into a MySQL database you have to convert it to a SQL statement. This can be done manually or by a library.
$data = array("one", "two", "tree"); // output one, two, three $insert_data = implode(",", $data); or $insert_data = json_encode($data); Thats for inserting data in single column. While retrieving you can do explode() or json_decode() to get the return data and can use them in the multi-select again.
You can not insert an array directly to MySQL as MySQL doesn't understand PHP data types. MySQL only understands SQL. So to insert an array into a MySQL database you have to convert it to a SQL statement. This can be done manually or by a library. The output should be an INSERT
statement.
Update for PHP7
Since PHP 5.5
mysql_real_escape_string
has been deprecated and as of PHP7 it has been removed. See: php.net's documentation on the new procedure.
Original answer:
Here is a standard MySQL insert statement.
INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)
If you have a table with name fbdata
with the columns which are presented in the keys of your array you can insert with this small snippet. Here is how your array is converted to this statement.
$columns = implode(", ",array_keys($insData)); $escaped_values = array_map('mysql_real_escape_string', array_values($insData)); $values = implode(", ", $escaped_values); $sql = "INSERT INTO `fbdata`($columns) VALUES ($values)";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With