I have three functions (insert-> for inserting data to database, update-> for updating data and save->it uses try catch)
function save($record,$pk)
{
try{
$this->insert($record);
}
catch(Exception $e)
{
$this->update($record,$pk);
}
}
function insert($record) {
global $pdo;
$keys = array_keys($record);
$values = implode(', ', $keys);
$valuesWithColon = implode(', :', $keys);
$query = 'INSERT INTO ' . $this->table . ' (' . $values . ') VALUES (:' . $valuesWithColon . ')';
$stmt = $pdo->prepare($query);
$stmt->execute($record);
}
function update($record,$pk)
{
global $pdo;
$parameters=[];
foreach ($record as $key => $value) {
$parameters[]=$key .'= :'. $key;
}
$list=implode(', ',$parameters);
$query="UPDATE $this->table SET $list WHERE $pk=:pk";
$record['pk']=$record[$pk];
$stmt=$pdo->prepare($query);
$stmt->execute($record);
}
the insert and update function works correctly. I want to use the save function to insert the data if not exists and replace the data if same PK exists.
My code to insert is:
if(isset($_POST['save'])){
unset($_POST['save']);
$department->save($_POST,'id');
}
The problem is: if there is no duplicate value, it inserts into the database. But if there is duplicate value(PK), it doesn't update into the database.
My array contains
Array
(
[id] => 1
[title] =>test
[description] =>description
)
It shows blank when i try to update via form.
P.S: If I replace "save" with "update" then it is updated in the database. But try catch of "save" is not working