Reputation: 628
The logic has me confused. I want to write one function to handle multiple forms. I have eight order forms, on different pages. They all use the same database. The function will need to handle insert functions OR update functions.
What I wrote before I got stumped:
// I might want to move this IF further down in the logic
// I wasn't sure what to put here in it's place.
if(isset($_POST['submitInsert']))
{
// setting up a loop to go through all the POST values
foreach($_POST as $name => $value)
{
// make sure POST values are set before wasting
// any time doing stuff with them
if($value!="")
{
// checking if the POST value is an array because
// an array would have to be handled differently
if(!is_array($value))
{
// Just printing info for now, Thinking maybe I should
// do an IF here to check for insert/update
echo $name . " --- " . $value . "<br>";
}
else
{
// for an array, I'll need another foreach statement
echo "$name"." --- ";
print_r($value);
echo "<br/>";
}
}
}
}
More Info
I'm planning to switch between insert/update by naming the submit buttons 'submitInsert' or 'submitUpdate'. And after some data validation, check insert/update. After deciding this was the way to go, I realized I don't know how to start the function.
The form element names match the db field names, so the SQL query shouldn't be difficult.
Is there a better way to do this?
Upvotes: 1
Views: 171
Reputation: 311
if(isset($_POST['submit']))
{
//could use for loop but you know the fields you will be using for your sql.
$id = $_POST['id'];
$var1 = $_POST['var1'];
// Do a select see if it exists if it does use update else use insert.
$query = "SELECT * from table where ID = $id";
if($rowCount > 0)
{
$query = "Update table set var=$var1 where id = $id";
}
else
{
$query = "Insert into table (var1) VALUES ($var1)";
}
}
Upvotes: 2