Insert and Update data using Function in PHP, MySQL

Inserting or updating data using MySQL is not a tough job though my article is on the use of single function that is used to insert or update data into database. You would need to call the function and pass parameters into it. For insert, two parameters are required while for update there are three. Let’s first see the function followed by an example.

You can use the following table as an example:



For inserting data see this function:



Let’s understand this function. Function named ‘Insert’ takes two parameters. First is $table that may be any table of your database. And second is $data. Now this second is actually an array of elements. Here elements are columns and corresponding data to be inserted. I have used array_map to escape. For that see the example array below:



Here name, email and phone are column/field names of the MySQL table. Remember while creating an array of elements, please do not put comma at the end of last element, i.e, after “4565654545”. Now see the parameter passing in the following example.



This will return the primary ID of the table after insert.

Similarly, we will see the update function that will the existing data in the table. The update function:


In above function “Update”, there are three parameters passed to create a query. First is table name, second is the elements of array and the third is key ID of the table on which the data is to be updated. Now we will see the query that executes it using the above function and array of elements that is to update the row.



Here in the parameter “where id = ‘1’”, id is the primary key of the table and 1 is its first value and can be any number that is to be updated. Array of elements are altered a bit.

See the while as a single file



June 11, 2017 by suman singh

Add a Comment
