Update if record doesn't exist in MySQL DB
This is my table: (unique master key alias
)
$sql = "CREATE TABLE IF NOT EXISTS Articls
(
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(254) COLLATE utf8_persian_ci NOT NULL,
alias INT(10) UNSIGNED NOT NULL, # alias name for url
title VARCHAR(254) NOT NULL COLLATE utf8_persian_ci NOT NULL,
UNIQUE (alias)
) DEFAULT COLLATE utf8_persian_ci";
So, I want to insert a new record into the DB if alias
doesn't exist in the table, or update the table if an alias existed previously.
I have tried this with no success.
$sqlname = "name,alias,title";
$sqlValue = "'".$node['name']."','".$node['alias']."','".$node['title']."'";
$sql = "INSERT INTO Articls (".$sqlname.")
VALUES (".$sqlValue.")
ON DUPLICATE KEY UPDATE
(".$sqlname.") VALUES (".$sqlValue.")";
I've also tried this code with no success ... It just creates a new entry and doesn't update:
$sql = "INSERT INTO Articls (".$sqlname.")
VALUES (".$sqlValue.")
ON DUPLICATE KEY UPDATE title = 'test',alias = '".$node['alias']."'";
+3
source to share