I have a form which writes to a MySQL database.
For example:
Employee Number:
Name:
Age:
Height:
Weight:
The first field, employee number is a unique ID to one user.
I’d like it to be the case that if someone fills out the form with a different unique employee number it creates a new record, however if is filled out with the same number then it just writes the old record – so they can come back later and adjust submissions.
My current code for writing the database form the form looks like this:
try {
$pdo = new PDO('mysql:host=localhost; dbname=db1', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO table
(
Time,
Unique_ID,
q1,
q2,
q3
)
VALUES
(
now(),
:Unique_ID,
:q1,
:q2,
:q3
)');
$stmt->execute(array(
':Unique_ID => $UID,
':q1' => $q1,
':q2' => $q2,
':q3' => $q3
));
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
Any and all help much appreciated, thank you.
EDIT:
Based on @Adrian Cornish’s advice below I’ve adjusted the query to be a REPLACE statement:
It now reads:
try {
$pdo = new PDO('mysql:host=localhost; dbname=db1', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('REPLACE INTO table
(
Time,
Unique_ID,
q1,
q2,
q3
)
VALUES
(
now(),
:Unique_ID,
:q1,
:q2,
:q3
)');
$stmt->execute(array(
':Unique_ID => $UID,
':q1' => $q1,
':q2' => $q2,
':q3' => $q3
));
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
Additionally I have edited the table strucutre in the MySQL database such that the ‘Unique_ID’ field now has the properties ‘Not Null’ and ‘Unique Index’, as the documents at:
http://dev.mysql.com/doc/refman/5.6/en/replace.html
State:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
However, upon attempting to enter data twice for the same Unique_ID I’m getting the error:
Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '90210' for key 'Unique_ID_UNIQUE'
Something I’m missing? Thank you
You could
SELECTon your employee number, if a row is returned, then issue a subsequentUPDATE, ortherwise anINSERTquery. That’s the manual way.You could achieve the same result with INSERT … ON DUPLICATE KEY UPDATE, but that won’t be as flexible.