简体   繁体   English

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

[英]how to update one or more fields ignoring the empty fields into mysql database?

i am seeking help on ignoring null values for updating the mysql database:-我正在寻求有关忽略 null 值以更新 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' ");

how do i incorporate an option where the user can only select one or all fields for updation.我如何合并一个选项,用户只能 select 一个或所有字段进行更新。

i tried using the following code based on responses received but it does the same thing.我尝试根据收到的响应使用以下代码,但它做同样的事情。 overwrites the existing data with the blank ones.用空白数据覆盖现有数据。

$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());

Firstly remember to escape any strings coming to you via POST, GET, or REQUEST (read up on SQL injection attacks if you're unsure why).首先要记住通过 POST、GET 或 REQUEST 转义任何给您的字符串(如果您不确定原因,请阅读 SQL 注入攻击)。

Something like this might work:像这样的东西可能会起作用:

$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 : Do not ever simply loop through your $_POST array to create a SQL statement.注意:永远不要简单地遍历 $_POST 数组来创建 SQL 语句。 An opponent can add extra POST fields and possibly cause mischief.对手可以添加额外的 POST 字段并可能造成恶作剧。 Looping through a user input array can also lead to an injection vector: the field names need to be added to the statement, meaning they're a potential vector.遍历用户输入数组也可能导致注入向量:字段名称需要添加到语句中,这意味着它们是潜在向量。 Standard injection prevention techniques (prepared statement parameters, driver-provided quoting functions) won't work for identifiers.标准注入预防技术(准备好的语句参数、驱动程序提供的引用函数)不适用于标识符。 Instead, use a whitelist of fields to set, and loop over the whitelist or pass the input array through the whitelist.相反,使用字段的白名单进行设置,并在白名单上循环或通过白名单传递输入数组。

You need to build your query.您需要构建您的查询。 Something like this:像这样的东西:

$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'";

The last update field: Cust_Name = '$cst' basically is to 'remove' the last comma.最后一个更新字段:Cust_Name = '$cst' 基本上是“删除”最后一个逗号。

Keeping in mind that $_POST values should be cleaned before use, and that all $_POST values are strings, so an empty field is '' and not null, something like this will work:请记住,在使用之前应该清理 $_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";

This should work (the MySQL way):这应该有效(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) . '";

I've tried to keep the columns and variables to what you have posted in your question, but feel free to correct as per your schema.我已尝试将列和变量保留为您在问题中发布的内容,但请随时根据您的架构进行更正。

Hope it helps.希望能帮助到你。

Loop over the optional input fields, building up which fields to set.循环可选输入字段,建立要设置的字段。 The field names and values should be kept separate so you can use a prepared statement.字段名称和值应分开保存,以便您可以使用准备好的语句。 You can also loop over required fields as a basic validation step.作为基本验证步骤,您还可以遍历必填字段。

# 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.
        ...
    }
}

This should be handled in a data access layer designed to map between the database and program objects.这应该在数据库和程序对象之间设计为 map 的数据访问层中处理。 If you're clever, you can write a single method that will work for arbitrary models (related forms, tables and classes).如果你很聪明,你可以编写一个适用于任意模型的单一方法(相关的 forms、表和类)。

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'
");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM