2013-03-03 91 views
0

我已经在php中创建了一个配置文件页面,其中用户使用表单可以将他的电话号码保存在数据库中名为profile的表中。如果用户决定改变他的电话号码,可以轻易地去改变它并再次保存。我唯一的问题是以下几点。假设用户想要删除他的电话号码。如果他去表格删除他的号码(使字段为空)并按保存,电话号码不会更改为空值并继续保留以前的号码。任何想法如何改变这个以保持一个空值?窗体保存空值php

这是我的代码形式:

<form action="" method="POST" >  

<?php 

if (isset($_GET['success']) === true && empty($_GET['success'])===true){ 
    echo'Profile Updated Sucessfuly'; 
    }else{ 
    if(empty($_POST) === false && empty($errors) === true){ 
    $update_data_profile = array('telephone' => $_POST['telephone']); 

      update_user_profile($session_user_id, $update_data_profile); 
     header('Location: profile_update.php?success');        
     exit(); 

    }else if (empty($errors) === false){ 
     echo output_errors($errors); 
     } 

    ?> 

Telephone<input name="telephone" type="text" size="25" value="<?php echo $user_data_profile['telephone']; ?>"/> 
<input type="submit" value="" name="submit"/> 
</form> 

这是我的功能分派数据来分析表:

function update_user_profile($user_id, $update_data_profile){ 

    $result = mysql_query("select user_id from profile where user_id = $user_id limit 1"); 

    if(mysql_num_rows($result) === 1){ 

    $update = array(); 
     array_walk($update_data_profile, 'array_sanitize'); 

    foreach($update_data_profile as $field => $data){ 
    if(!empty($data)){ 
     $update[]='`' . $field . '` = \'' . $data . '\''; 
    } 
    } 

    if(isset($update) && !empty($update)){ 

    mysql_query(" UPDATE `profile` SET " . implode(', ', $update) . " WHERE `user_id` = $user_id ") or die(mysql_error()); 
} 
    } 
    else{ 

$user_id = $update_data_profile['user_id'] ; 

if(count($update_data_profile)){ 

$columns = array(); 
$values = array(); 

    foreach($update_data_profile as $field => $data){ 
    $columns[] = $field; 
    $values[] = $data; 
    } 
} 

mysql_query(" INSERT INTO `profile` (" . implode(",", $columns) .") values ('" . implode("','", $values) . "')") or die (mysql_error()); 

} 

} 

回答

1

你只更新字段,如果数据不为空。

看到这一行:

if(!empty($data)){ 
+0

确定并将其更改为什么? – 33528 2013-03-03 16:41:00

+0

您可以将其删除; // if(!empty($ data)){ $ update [] ='''。 $字段。 ''= \''。 $数据。 '\''; //} – Anonymous 2013-03-03 16:41:55

1

因为你明确忽略空值与此:

if(!empty($data)) 
+0

我应该如何改变它以接受空值? – 33528 2013-03-03 16:41:56

+0

那么,如果你想让所有字段都设置为空,你可以删除它。如果它只是你想让用户清除的电话,你可以做一些类似'if(!empty($ data)|| $ field =='telephone')' – juco 2013-03-03 16:43:50

0

由于空()函数可以确认失踪,而假的元素,你可以” t只需将它传递给SQL查询即可。所以,如果你想真正产生这些项目的查询,你需要做这样的事情明确设定值:

if (empty($data)) { 
    $update[] = "`{$field}` = ''" ; 
} else { 
    $update[] = "`{$field}` = '{$data}'" ; 
} 

如果你正在编写PHP 5.3或以上,你也可以更换if..else声明并通过使用三元运算符(条件赋值)缩短您的代码做这样的事情:

$update[] = (empty($data)) ? "`{$field}` = ''" : "`{$field}` = '{$data}'";