Reputation: 73
I have a page with 3 columns, the first 2 columns have forms while the third shows information.
Whenever the page is called, information corresponding to the first form will already exist, however the second form can be used to insert new data or update existing.
The code I have at the moment:
<?php
require_once 'connect.php';
$formType = $_POST['formType'];
$id = $_POST['id'];
$favColor= $_POST['favColor'];
$favFood= $_POST['favFood'];
$country = $_POST['country'];
if($_POST['formType'] == 'guestCosts'){
$sth = $dbh->prepare("INSERT INTO info (id, favColor, favFood, country)
VALUES ('$id', '$favColor', '$favFood', '$country')");
$sth->execute();
}elseif($_POST['formType'] == 'guestCosts'){
$sth = $dbh->prepare("UPDATE info SET favColor = '$favColor', favFood = '$favFood', country = '$country' WHERE id = '$id'");
$sth->execute();
}
$dbh =null;
?>
The problem I'm having is that I see now way to distinguish between when I should do an UPDATE vs when I should do an INSERT.
The page that generates the form does a query to populate the form with the values from the database. I thought of adding a hidden field if the database is empty for a particular id for example:
<input type = "hidden" name ="action" value="insert" />
However I'm not sure passing a variable between pages is the most efficient way. Is there a better way to do what I am trying to do?
Upvotes: 0
Views: 65
Reputation: 1822
Take a look at MySQL INSERT ON DUPLICATE KEY UPDATE
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Upvotes: 1