如何更新一个或多个字段忽略空字段到mysql数据库?

时间:2011-06-29 14:13:41

标签: php mysql

我正在寻求帮助忽略更新mysql数据库的空值: -

$cst = $_POST['custname'];
$a = $_POST['tel'];
$b = $_POST['fax'];
$c = $_POST['email'];
$sql = mysql_query("UPDATE contacts SET TEL = '$a', FAX = '$b', EMAIL = '$c'
                    WHERE Cust_Name = '$cst' ");

如何合并一个选项,用户只能选择一个或所有字段进行更新。

我尝试根据收到的回复使用以下代码,但它做了同样的事情。用空白数据覆盖现有数据。

$upd = mysql_query("UPDATE custcomm_T SET 
Telephone = ".(is_null($a)?'Telephone':"'$a'").",
Fax = ".(is_null($b)?'Fax':"'$b'").",
Mobile = ".(is_null($c)?'Mobile':"'$c'").",
EMail = ".(is_null($d)?'EMail':"'$d'").",
trlicense = ".(is_null($e)?'trlicense':"'$e'").",
trlicexp = ".(is_null($f)?'trlicexp':"'$f'")."
WHERE Cust_Name_VC = '$g' ") or die(mysql_error());

6 个答案:

答案 0 :(得分:4)

首先记住要通过POST,GET或REQUEST来逃避任何字符串(如果你不确定原因,请阅读SQL注入攻击)。

这样的事可能有用:

$semaphore = false;
$query = "UPDATE contacts SET ";
$fields = array('tel','fax','email');
foreach ($fields as $field) {
   if (isset($_POST[$field]) and !empty($_POST[$field]) {
     $var = mysql_real_escape_string($_POST[$field]);
     $query .= uppercase($field) . " = '$var'";
     $semaphore = true;
   }
}

if ($semaphore) {
   $query .= " WHERE Cust_Name = '$cst'";
   mysql_query($query);
}

NB :不要简单地遍历$ _POST数组来创建SQL语句。对手可以添加额外的POST字段并可能导致恶作剧。循环通过用户输入数组也可以导致注入向量:需要将字段名称添加到语句中,这意味着它们是潜在的向量。标准注入防止技术(预处理语句参数,驱动程序提供的引用函数)不适用于标识符。而是使用字段白名单来设置,并循环白名单或通过白名单传递输入数组。

答案 1 :(得分:1)

您需要构建查询。像这样:

$query = 'update contacts set ';
if ($_POST['tel'] != '') $query .= 'TEL="'.$_POST['tel'].'", ';
if ($_POST['fax'] != '') $query .= 'FAX="'.$_POST['fax'].'", ';
if ($_POST['email'] != '') $query .= 'EMAIL="'.$_POST['email'].'", ';
$query .= "Cust_Name = '$cst' where Cust_Name = '$cst'";

最后一个更新字段:Cust_Name ='$ cst'基本上是'删除'最后一个逗号。

答案 2 :(得分:0)

请记住,$ _POST值应该在使用前清除,并且所有$ _POST值都是字符串,所以空字段是''而不是null,这样的东西可以工作:

        foreach ($_POST as $var=>$value) {
            if(empty($value)) continue; //skip blank fields (may be problematic if you're trying to update a field to be empty)
            $sets[]="$var= '$value";

        }
        $set=implode(', ',$sets);
        $q_save="UPDATE mytable SET $set WHERE blah=$foo";

答案 3 :(得分:0)

这应该有效(MySQL方式):

"UPDATE `custcomm_T`
SET `Telephone` = IF(TRIM('" . mysql_real_escape_string($a) . "') != '', '" . mysql_real_escape_string($a) . "', `Telephone`),
SET `Fax` = IF(TRIM('" . mysql_real_escape_string($b) . "') != '', '" . mysql_real_escape_string($b) . "', `Fax`),
SET `Mobile` = IF(TRIM('" . mysql_real_escape_string($c) . "') != '', '" . mysql_real_escape_string($c) . "', `Mobile`),
SET `EMail` = IF(TRIM('" . mysql_real_escape_string($d) . "') != '', '" . mysql_real_escape_string($d) . "', `EMail`),
SET `trlicense` = IF(TRIM('" . mysql_real_escape_string($e) . "') != '', '" . mysql_real_escape_string($e) . "', `trilicense`),
SET `trlicexp` = IF(TRIM('" . mysql_real_escape_string($f) . "') != '', '" . mysql_real_escape_string($f) . "', `trlicexp`)
WHERE Cust_Name_VC = '" . mysql_real_escape_string($g) . '";

我已尝试将列和变量保留在您在问题中发布的内容,但可以根据您的架构进行更正。

希望它有所帮助。

答案 4 :(得分:0)

遍历可选输入字段,构建要设置的字段。字段名称和值应保持独立,以便您可以使用预准备语句。您还可以循环使用必填字段作为基本验证步骤。

# arrays of input => db field names. If both are the same, no index is required.
$optional = array('tel' => 'telephone', 'fax', 'email');
$required = array('custname' => 'cust_name');

# $input is used rather than $_POST directly, so the code can easily be adapted to 
# work with any array.

$input =& $_POST;

/* Basic validation: check that required fields are non-empty. More than is 
 necessary for the example problem, but this will work more generally for an 
 arbitrary number of required fields. In production code, validation should be 
 handled by a separate method/class/module.
 */
foreach ($required as $key => $field) {
    # allows for input name to be different from column name, or not
    if (is_int($key)) {
        $key = $field;
    }
    if (empty($input[$key])) {
        # error: input field is required
        $errors[$key] = "empty";
    }
}
if ($errors) {
    # present errors to user.
    ...
} else {
    # Build the statement and argument array.
    $toSet = array();
    $args = array();
    foreach ($optional as $key => $field) {
        # allows for input name to be different from column name, or not
        if (is_int($key)) {
            $key = $field;
        }
        if (! empty($input[$key])) {
            $toSet[] = "$key = ?";
            $args[] = $input[$key];
        }
    }
    if ($toSet) {
        $updateContactsStmt = "UPDATE contacts SET " . join(', ', $toSet) . " WHERE cust_name = ?";
        $args[] = $input['custname'];
        try {
            $updateContacts = $db->prepare($updateContactsStmt);
            if (! $updateContacts->execute($args)) {
                # update failed
                ...
            }
        } catch (PDOException $exc) {
            # DB error. Don't reveal exact error message to non-admins.
            ...
        }
    } else {
        # error: no fields to update. Inform user.
        ...
    }
}

这应该在数据访问层中处理,该数据访问层旨在在数据库和程序对象之间进行映射。如果你很聪明,你可以编写一个适用于任意模型(相关表格,表格和类)的方法。

答案 5 :(得分:-1)

mysql_query("
    UPDATE contacts 
    SET 
        TEL = ".(is_null($a)?'TEL':"'$a'").", 
        FAX = ".(is_null($b)?'FAX':"'$b'").", 
        EMAIL = ".(is_null($c)?'EMAIL':"'$c'")."
    WHERE Cust_Name = '$cst'
");