My query is supposed to insert a row when there isn't already an existing one, but I don't know how to put the parameters correctly. There are 8 parameters which go into a new row, but if doing an update only 6 columns should be updated. But when doing update it says I provided the wrong amount of variable placeholders , 14 placeholders for 8 variables. See here:
$event_id = "value";
$status_type = "value";
$sport_name = "value";
$startdate = "value";
$ut = "value";
$name = "value";
$value_home = "value";
$value_away = "value";
$sql = "INSERT INTO wp_mytable "
. "(event_id,status_type, sport_name, startdate, ut, name, value_home, value_away) "
. "VALUES (%s,%s,%s,%s,%s,%s,%s,%s) "
. "ON DUPLICATE KEY UPDATE status_type = %s, startdate = %s,ut = %s, name = %s, value_home = %s, value_away = %s";
$sql = $wpdb->prepare($sql,$event_id, $status_type,$sport_name,$startdate,$ut ,$name ,$value_home ,$value_away );
$wpdb->query($sql);
The VALUES
placeholders are needed for inserts I guess, but they also count towards the "on duplicate key" updates..
I also tried to write like this:
"ON DUPLICATE KEY UPDATE status_type = status_type, startdate = startdate,ut = ut, name = name, value_home = value_home, value_away = value_away ";
but that didn't work - there was no update, but instead it seems a new row was created and deleted. So how should the correct query look like?
I found a solution that worked here: stackoverflow.com/questions/22699598/prepared-statement-with-on-duplicate-key Each of the columns for the update is put within "VALUES()
".
$sql = "INSERT INTO wp_mytable "
. "(status_type, startdate,ut ,name ,value_home ,value_away ,sport_name ,event_id ) "
. "VALUES (%s,%s,%s,%s,%s,%s,%s,%s) "
. "ON DUPLICATE KEY UPDATE status_type = VALUES(status_type), sport_name=VALUES(sport_name), "
. "startdate = VALUES(startdate),ut = VALUES(ut), name = VALUES(name), "
. "value_home = VALUES(value_home), value_away = VALUES(value_away)";
$sql = $wpdb->prepare($sql,$status_type,$startdate,$ut ,$name ,$value_home ,$value_away, $sport_name, $event_id );