I have this method which takes in an array of integers and creates a row in the DB for each one of them. The array can be variable length, can have 1 element, or 100. I only want to insert if the record does not exist already, for each of the integer in $data array. So if $data = [1,2,3]
and in the database record for 2 already exists, it will not add another one, but it will add new ones for 1 and 3. So if you were to run this same query again, nothing will be inserted.
This is the current syntax:
public function addUserJobAttributes($account, $data)
{
$data = [1,2,3,4,5,6,7];
try {
$qstring = '';
$qarray = [];
$i = 1;
foreach ($data as $item) {
$qstring .= '(:userId_' .$i. ', :jobAttributrValueId_'.$i.'),';
$qarray[':userId_'.$i] = $account->id;
$qarray[':jobAttributrValueId_'.$i] = $item;
$i++;
}
$qstring = rtrim($qstring, ',');
$db = new \Db();
$query = $db->conn->prepare("INSERT INTO userjobattributes (userId, jobAttributeValueId)
VALUES $qstring");
$query->execute($qarray);
$db = null;
} catch (\Exception $e) {
$this->logger->log($e->getMessage());
$db = null;
throw new \ELException('Query could not be executed', 500, null, 'Dodgy SQL');
}
}