My variable sqlConditions is only suppose to append when the user inputs text for that field. I put "if(isset($_POST['example']))" to check for this, however this doesn't appear to stop each variable from appending.
For example: if the user only inserts text in the "lastname" field, the $query variable should return:
UPDATE students SET lastname = whateveruserputin
However, it looks like this:
UPDATE students SET lastname = test , firstname = , major = , gpa =
How can I fix this!? I would really like to get this code working. Thanks in advance.
Code:
//connect to server
if(isset($_POST['submit']))
{
$id=$_POST['id'];
$lastname=$_POST['lastname'];
$firstname=$_POST['firstname'];
$color=$_POST['color'];
$number=$_POST['number'];
//need id to be filled and need at least one other content type to change
if(empty($id) || empty($lastname) and empty($firstname) and empty($color) and empty($number))
{
echo "<font color='red'>Invalid Submission. You did not enter an ID or did not input an additional form element. </font><br/>";
}
else // if all the fields are filled (not empty)
{
$sqlConditions = array();
if(isset($_POST['lastname'])){
$lastName = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
$sqlConditions[] = 'lastname = ' . $lastName;
} else {
$lastName = '';
}
if(isset($_POST['firstname'])){
$firstName = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
$sqlConditions[] = 'firstname = ' . $firstName;
} else {
$firstName = '';
}
if(isset($_POST['color'])){
$color = filter_var($_POST['color'], FILTER_SANITIZE_STRING);
$sqlConditions[] = 'color = ' . $color;
} else {
$color = '';
}
if(isset($_POST['number'])){
$number = filter_var($_POST['number'], FILTER_SANITIZE_STRING);
$sqlConditions[] = 'number = ' . $number;
} else {
$number= '';
}
print $sqlConditions;
$query = 'UPDATE students SET ' . join (' , ', $sqlConditions);
print $query;
insert data to database
//$query = mysql_query("UPDATE students SET lastname = '$lastname', firstname = '$firstname', color = '$color', number = '$number'
//WHERE id = '$id'");
//if (!query)
//{
//die('Error: ' . mysql_error());
//}
// Close connection to the database
mysql_close($con);
}
}