Reputation: 3
I understand this question might have been asked, but i tried using the solutions i found here and they didn't work for me. I need to update data in my database if the email column exists, if not it should insert a new record. Here is my code below.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'mbf';
$dbconn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($db);
$dat = date("Y-m-d H:i:s");
$date = new DateTime();
$date->modify('+4 weeks');
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$dat = $_POST['date'];
$ghdate = $_POST['ghdate'];
$amount = $_POST['amount'];
$iniamount = $_POST['iniamount'];
$outamount = $_POST['outamount'];
$ghamount = $_POST['ghamount'];
$query = "INSERT INTO donation (email, date, ghdate, amount,
inamount, outamount, ghamount) VALUES ('$email', '$dat',
'$ghdate','$amount',
'$iniamount', '$outamount', '$ghamount')
ON DUPLICATE KEY UPDATE
email='$email', date='$dat', amount='$amount', inamount='$iniamount',
outamount='$outamount', ghamount='$ghamount'";
if(mysql_query($query))
{
echo "<script>alert('Donation of $amount was successful');</script>";
}
else
{
echo "<script>alert('FAILED TO INSERT');</script>";
}
}
?>
it does not update the email column rather it inserts a new record.
Upvotes: 0
Views: 32
Reputation: 1198
ON DUPLICATE KEY UPDATE
statement works only if any field value violates UNIQUE / PRIMARY KEY constraint. Make sure the email field has UNIQUE constraint in the table schema.
Upvotes: 2