phpmysqlarrays

Insert array into MySQL database with PHP


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.


Solution

  • 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));
    $link = mysqli_connect($url, $user, $pass,$db);
    $escaped_values = array_map(array($link, 'real_escape_string'), array_values($insData));
    
    $values  = implode("', '", $escaped_values);
    $sql = "INSERT INTO `fbdata`($columns) VALUES ('$values')";