开发者

PHP/mysql conditional update query

开发者 https://www.devze.com 2023-02-15 18:43 出处:网络
I am trying to submit data to a database.I have an update form that has several fields on it that pulls data from the database into the fields.Submitting it updates the data in the database.The two fi

I am trying to submit data to a database. I have an update form that has several fields on it that pulls data from the database into the fields. Submitting it updates the data in the database. The two fields i am concerned with our two image uploaders that i have in the form. I have been doing this successfully when i have only one image uploader on the page, but can't wrap my head around the conditional syntax when i add the second one. Below is the code that i am using for the forms that have only one image uploader. It looks to see if that submitted element is empty. If so, it runs an update statement and leaves out the image variable. If the image variable is not empty it runs an update statement with that field added to the statement.

if($imgProfileFull == ""){
$query = "update students set `nameFirst` = '$nameFirst', `nameLast` = '$nameLast', `profile` = '$profile', `priority` = '$priority', `active` = '$active', `_modifiedDate` = '$_modifiedDate' where `id` = '$id'";
}else{
if((($_FILES["image"]["type"] == "image/jpeg")
|| ($_F开发者_高级运维ILES["image"]["type"] == "image/pjpeg"))
&& ($_FILES["image"]["size"] < 500000))
{
  if($_FILES["image"]["error"] > 0){
    header("location:students.php?file=error");
  }else{
    move_uploaded_file($_FILES["image"]["tmp_name"],
    "../images/students/full/" . $imgProfileFull);
  }
}else{
  header("location:students.php?file=error");
}
$query = "update students set `imgProfileFull` = '$imgProfileFull', `nameFirst` = '$nameFirst', `nameLast` = '$nameLast', `profile` = '$profile', `priority` = '$priority', `active` = '$active', `_modifiedDate` = '$_modifiedDate' where `id` = '$id'";
}

How would i write my update statement to include another image field. The variable would be $imgProfileThumb. Basically i want to update the two image columns in the database if, and only if, they are NOT empty. This is because the way the form is built, the image field is technically always empty unless an image actually gets uploaded. Any thoughts? Thanks!!


You can use an if statement to create your query dynamically.

$query = "UPDATE students SET ";

if ($imgProfileFull !== ""){
    $query .= "`imgProfileFull` = '$imgProfileFull', ";
}

if ($imgProfileThumb !== ""){
    $query .= "`imgProfileThumb` = '$imgProfileThumb', ";
}

$query .= "`nameFirst` = '$nameFirst',
           `nameLast` = '$nameLast',
           `profile` = '$profile',
           `priority` = '$priority',
           `active` = '$active',
           `_modifiedDate` = '$_modifiedDate'
           WHERE `id` = '$id'";

You may also wish to use mysql_real_escape_string for your string data if you are not already doing so.

0

精彩评论

暂无评论...
验证码 换一张
取 消