Description
This function insert new records in a table using associative array or update the record if same record already exists. MySQL INSERT ON DUPLICATE KEY UPDATE statement
to update data if a duplicate in the UNIQUE index or PRIMARY KEY error occurs when you insert a row into a table.
Function Defination
public function insertOnDuplicateUpdate($dbTableName, $insertData, $updateData)
Parameters Details
| Details | Type | Example |
|---|---|---|
| $dbTableName - Table name to insert records | string | Any table name like "orderTable", "wp_posts" etc |
| $insertData - Associative array of records to be inserted, with columnName as key and columnValue as value | assoc. array | array("orderNumber"=>1001, "customerName"=>"John Cena", "address"=>"140 B South Jercy") |
| $updateData - Associative array of records to be inserted, with columnName as key and columnValue as value | assoc. array | array("orderNumber"=>1001, "customerName"=>"John Cena", "address"=>"140 B South Jercy") |
Examples
$pdomodel = new PDOModel(); //create object of the PDOModel class
$pdomodel->connect("localhost", "root", "", "pdocrud");//connect to database
//Example 1
$insertData = array("id"=> "1068","first_name" => "bob", "last_name" => "builder");
$updateData = array("first_name" => "boboo", "last_name" => " the builder");
$pdomodel->insertOnDuplicateUpdate("employee", $insertData, $updateData);
Result/Output
Record will be inserted in database
Debug
| Option | Details | Example |
|---|---|---|
| $pdomodel->getLastQuery(); | Return last query executed | INSERT INTO `employee` (`id`,`first_name`,`last_name`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `first_name`=?,`last_name`=? Errors (if any) |
| print_r($pdomodel->error) | Print errors (if any) | |
| $pdomodel->lastInsertId | Return last insert Id | 53 |
| $pdomodel->rowsChanged; | Return Rows created/changed | 2 |