0

if I have a query with field 1 being a primary key:

$rep = "Replace into table (field1,field2) values ('value1','value2')";
$stmt = $db->query($rep);

Is there a way to tell if mysql inserted the row, or found and replaced the row?

bart2puck
  • 2,378
  • 3
  • 21
  • 46

2 Answers2

1

For Posterity:

$rowCount = $stmt->rowCount();

if $rowCount == 1 it was an insert, if $rowCount == 2, it was a replace.

bart2puck
  • 2,378
  • 3
  • 21
  • 46
0

INSERT INTO AggregatedData (datenum,Timestamp) VALUES ("734152.979166667","2010-01-14 23:30:00.000") ON DUPLICATE KEY UPDATE Timestamp=VALUES(Timestamp)

To achieve this type of task mysql provide us DUPLICATE KEY UPDATE.

Below is the example how you will create new record if record is not exists in database otherwise it will update record

$rep = "INSERT into table (primaryField,field2) values ('value1','value2') ON DUPLICATE KEY UPDATE primaryField=VALUES(primaryField)";
$stmt = $db->query($rep);

For more detail you can read this https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

I think this will help you.

Lakhwinder Singh
  • 5,084
  • 5
  • 24
  • 47