How would I go about not sending the data to the database if the some of the fields are left empty? Right as of now, if a field is empty on the form, the database is replacing whatever was in the field with blank data
UPDATE: Forgot to mention, it doesn't matter if the some of the fields are left blank, that should be allowed.
My code
<?php
if (isset($_POST['eventname'], $_POST['date'], $_POST['eventvenue'] , $_POST['eventtime'], $_POST['eventcost'])){
$eventname = ($_POST['eventname']);
$eventdate = ($_POST['date']);
$eventtime = ($_POST['eventtime']) . ":00";
$eventvenue = ($_POST['eventvenue']);
$eventcost = ($_POST['eventcost']);
$result = mysql_query("UPDATE event set event_name = '" . $eventname . "', event_date = '" . $eventdate . "', event_time = '" . $eventtime . "', event_venue = '" . $eventvenue ."', event_cost = '" . $eventcost ."'");
}
?>
Try some thing like This
$query= "UPDATE event set ":
If(isset($var1)){
$query.= " var1=".$var1;
}else if (isset($var2)){
$query.= " var2=".$var2;
}
and so forth and then
$result = mysql_query($query);
You can read on PHP's function empty()
Example usage:
if(empty($eventname))
{
echo "You have not set event name";
} else {
mysqli_query(...);
}
As said on comments, do not use the deprecated mysql_*
functions, use either mysqli_* or PDO.
This is an example using prepared statements; it builds the update statement based on whether the field is empty (zero length) or not.
Afterwards, the prepared statement is executed.
$updates = [];
$parameters = [];
if (strlen($_POST['eventname'])) {
$updates[] = 'event_name = ?';
$parameters[] = $_POST['eventname'];
}
// ...
if (strlen($_POST['eventtime'])) {
$updates[] = "event_time = ?";
$parameters[] = $_POST[$field] . ':00';
}
if ($updates) {
$sql = sprintf('UPDATE event SET %s WHERE xxx', join(',', $updates));
$stmt = $db->prepare($sql);
$stmt->execute($parameters);
}