Create dynamic Mysql Insert Query Function in PHP using MYSQLi OOP

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 $connor $dbConn then change global $db to global $conn.


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.

Also read:

 

Posted in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *