Databases Reference
In-Depth Information
// See if we've arrived here after clicking the update button;
// if so, update the gift details.
if(isset($_POST['update']))
{
// Define an SQL query to list the gift IDs in the database
$query = "SELECT gift_id FROM gifts";
// Run the query through the connection
if (($result = @ mysqli_query($connection, $query))==FALSE)
showerror($connection);
// Process the submitted data for each gift ID in the database
while($row = @ mysqli_fetch_array($result))
{
$gift_id=$row["gift_id"];
// Update an existing gift if there is corresponding data
// submitted from the form
if(
isset($_POST["quantity" ][$gift_id]) &&
isset($_POST["description"][$gift_id]) &&
isset($_POST["color" ][$gift_id]) &&
isset($_POST["shop" ][$gift_id]) &&
isset($_POST["price" ][$gift_id])
)
update_or_insert_gift_data($connection, $gift_id);
}
// Process the data submitted in the form fields for the new
// gift; we had assigned this the index 0 in the HTML form.
update_or_insert_gift_data($connection, 0);
}
Now let's look at update_or_insert_gift( ) . This function extracts and cleans the data
of the various form fields from the $_POST array. It then verifies that all the fields contain
some data; if any field is empty, an error message is displayed, and the database is not
updated. The error message is not displayed if the data items belong to the last table
row—which is a blank row allowing the user to optionally enter data for a new gift—
and all the fields are empty. We check for this by concatenating all the fields with the
period or dot symbol ( . ). We display the message if we're processing any row but the
last one, and one of the fields is empty, or if it is the last row and the combined length
of all the concatenated strings is not zero.
If some data is available for each gift attribute, the script runs a REPLACE INTO query to
update the database. A REPLACE INTO query replaces any existing data for a given key,
or automatically creates a new entry if no data already exists for that key:
// Update the data for a gift with the specified gift ID; for a
// gift ID of 0, add a new gift to the database.
function update_or_insert_gift_data($connection, $gift_id)
{
// Extract the data items for the gift attributes from the $_POST array
$quantity =clean($_POST["quantity" ][$gift_id], 5);
 
Search WWH ::




Custom Search