[Snippet] PHP Code to Submit data into Database

Filled in Code Snippet
What is it?

Although we use the framework to submit data into the database, sometimes we need a pure PHP code to insert data into the database. Honestly, sometimes we forget the command to insert data into the database, because the framework has been easier for us.

And this morning, I get a case where I have to enter the data into the database without using the framework. I usually use cakephp.

Here are a few lines of code that is easy to learn.

?php
function mysql_insert($table, $inserts) {
    $values = array_map('mysql_real_escape_string', array_values($inserts));
    $keys = array_keys($inserts);
        
    return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (''.implode('','', $values).'')');
}
?>

For example:

<?php

mysql_insert('cars', array(
    'make' => 'Aston Martin',
    'model' => 'DB9',
    'year' => '2009',
));
?>

very easy right?

Meta Details