<?php
function upsert(PDO $db, string $table, array $row, array $updateCols): bool {
$cols = array_keys($row);
$colSql = '`' . implode('`,`', $cols) . '`';
$phSql = implode(',', array_fill(0, count($cols), '?'));
$updSql = implode(',', array_map(fn($c) => "`$c`=VALUES(`$c`)", $updateCols));
$sql = "INSERT INTO `$table` ($colSql) VALUES ($phSql) ON DUPLICATE KEY UPDATE $updSql";
$stmt = $db->prepare($sql);
$stmt->execute(array_values($row));
// MySQL: rowCount = 1 for insert, 2 for update, 0 for no-op
return $stmt->rowCount() === 1;
}
upsert($db, 'page_views', ['url'=>'/about','views'=>1], ['views']);
Create a free account and build your private vault. Share publicly whenever you want.