-1
4

2 回答 2

0

与创建 2 个数组相反,我只需创建一个包含所有变量的字符串,然后在 SQL 中进行 IF 条件检查。正如我之前所说,这是基于 Kitet 的这个例子

<?php 

$values=array();

//this will be an array of possible fields that are in your table
$possible=array('field1', 'field2', 'field3');

$i=0;
$len=count($_POST);
$query='update table_name set ';
foreach($_POST as $key => $value){
$k=htmlspecialchars($key);
$v=htmlspecialchars($value);
if(in_array($k, $possible)){
$query .= '`' .$k .'`' .'= IF("'.$v .'"= "", `' .$k .'`, "' .$v .'")'; //changes here!!!

if($i < ($len-1)) $query .= ', ';
$i++;
}
}
$query .= 'where table_id = '.$table_id;

$update_data= $db_con->prepare($query); // I prepare the statement here as a safety net  
$update_data->execute(); // the execute it

?>

现在一切都按预期工作:) 我希望这对其他人有所帮助。

于 2013-09-23T21:09:03.627 回答
0
<?php

  $values = ARRAY();


  $sql_query = "UPDATE `userData` SET `name`= ?, `submitDate`= ?, ";
  $values[] = $variable_name; //:name, now ?
  $values[] = $variable_date; //:submitDate, now ?

  if (!empty($v)) {
    $sql_query .= "`contacts`= ?,";
    $values[] = $v; //:contacts, now ?
  }

  $sql_query .= "`email`= ? WHERE `submit_id`= ?;";
  $values[] = $variable_email; //:email, now ?
  $values[] = $variable_submit_id; //:submit_id, now ?

  $contactDetails= $db_con->prepare($sql_query);
  $this_query->execute($values);

?>
于 2013-09-23T01:15:58.023 回答