Insert record is the most common operation used in database. But every time writing a query will be hectic. If you are working on framework (like codeigniter and laravel), they usually come up with query builder class.
But if you are writing procedural PHP then you have to take care of CRUD queries yourself. I mostly worked with PHP frameworks but sometime if I require to work on procedural PHP then I must create different function for Mysql operations. One of them list insert operation.
Below is the insert function i usually use in my PHP projects.
PHP MySQL Insert Function:
Below insert function takes 3 parameters.
- Parameter 1: Mysql tabl name.
- Parameter 2: Array of data. Must be associative array with column name as key and data as value.
- Parameter 3: Return affected rows or insert id. By default it is false and return affected rows. But if you want get last insert id then pass this as true.
$db
is a database connection object. If you have mysql object with different name like $conn
or $dbConn
then change global $db to global $conn.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function insert($table, array $dataArray, $returnID = false) { global $db; $getColumnsKeys = array_keys($dataArray); $implodeColumnKeys = implode(",",$getColumnsKeys); $getValues = array_values($dataArray); $implodeValues = "'".implode("','",$getValues)."'"; $qry = "insert into $table (".$implodeColumnKeys.") values (".$implodeValues.")"; $db->query($qry); if($returnID == true) { return $db->insert_id; } else { return $db->affected_rows; } } |
How to use insert function:
Let say I have a contact_us table in database with name, email, subject and message fields and i want to insert data in contact_us table using above insert function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$db = new mysqli("localhost","root","","demo"); if($db->connect_error) { die("Database Connection Error, Error No.: ".$db->connect_errno." | ".$db->connect_error); } $array = array( "name"=>"Ahsan Zameer", "email"=>"ahsan@wdb24.com", "subject"=>"This is subject", "message"=>"This is my dummy message" ); echo insert("customers",$array,true); |
Also read:
- PHP MYSQLi Object Oriented Tutorial for Beginners
- PHP cURL get request with parameters
- PHP CURL tutorial with Examples
- PHP read text file and insert into MySQL database
- How to store textarea value in database in PHP