[Snippet] PHP Code to Submit data into Database

Monday, April 6th, 2015 - Code Snippet

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?

[Snippet] PHP Code to Submit data into Database | Fareed Abdullah | 4.5