从表单中编写PHP更新代码

Like the title itself is telling i would like to write soms PHP update mysql code into a shorter way

Here is an example block of the php code:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

  $getid = $_SESSION['id']

  if (empty($_POST['name']) {
  $name = ' ',
  }

  if (empty($_POST['firstname']) {
  $firstname = ' ',
  }

  if (empty($_POST['address']) {
  $address = ' ',
  }

  $upregstmt = $dbh->prepare("UPDATE contacts SET c_firstname = ?, c_name = ?, c_address = ? WHERE c_id = ?");  
  $upregstmt->bindParam(1, $firstname);
  $upregstmt->bindParam(1, $name);
  $upregstmt->bindParam(1, $address);
  $upregstmt->bindParam(1, $getid);
  $upregstmt->execute();


}

I have a much larger form where not everything will be filled in and must stay empty so i have to at an empty variable in that case.

Question: isn't there a walk around for this (a parameter you can send with your query for example that it doesn't give me an empty variable error?) and cant the other code been written smaller?

You can shorten it a bit doing this:

$exludeArray = array("submit");
foreach ($_POST as $key => $value) {
    if (!in_array($key, $excludeArray))
        $upregstmt->bindParam(1, (empty($value) ? " " : $value));
}

It loops through your $_POST global, exclude things you dont want to add, such as the submit button.

It is untested, but should give you an idea on how to approach this.