更新个人资料php
发布时间:2020-12-13 22:47:28 所属栏目:PHP教程 来源:网络整理
导读:我在php中创建了一个配置文件页面.该页面包含地址和电话字段,并提示用户插入其数据.然后将数据保存在名为profile的表中. 一切正常,但问题是表只有在包含已经数据时才更新.我怎样才能修改它(可能是我在函数中的 mysql查询),这样数据就会输入到表中,即使它是空
我在php中创建了一个配置文件页面.该页面包含地址和电话字段,并提示用户插入其数据.然后将数据保存在名为profile的表中.
一切正常,但问题是表只有在包含已经数据时才更新.我怎样才能修改它(可能是我在函数中的 mysql查询),这样数据就会输入到表中,即使它是空的.有没有像我可以使用的UPDATE OR INSERT INTO语法? 谢谢 <?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( 'address' => $_POST['address'],'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); } ?> 然后使用以下功能 function update_user_profile($user_id,$update_data_profile){ $update = array(); array_walk($update_data_profile,'array_sanitize'); foreach($update_data_profile as $field => $data ) { $update[]='`' . $field . '` = '' . $data . '''; } mysql_query(" UPDATE `profile` SET " . implode(',',$update) . " WHERE `user_id` = $user_id ") or die(mysql_error()); } 解决方法
我是psu发布的答案的新手,并且肯定会检查它,但是从快速阅读中,你需要在使用这些特殊语法时非常小心.
我想到的一个原因是:您不知道您要插入或更新信息的表格可能会发生什么.如果定义了多个唯一身份验证,那么您可能会遇到严重问题,这在扩展应用程序时很常见. 2替换为语法是我很少希望在我的应用程序中发生的功能.因为我不想从表中已经存在的行中的colomns中丢失数据. 我不是说他的答案是错的,只是说明在使用它时需要采取预防措施,因为上述原因和可能的原因. 如第一篇文章中所述,我可能是这样做的新手,但在这个时刻我更喜欢: $result = mysql_query("select user_id from profile where user_id = $user_id limit 1"); if(mysql_num_rows($result) === 1){ //do update like you did } else{ /** * this next line is added after my comment,* you can now also leave the if(count()) part out,since the array will now alwayss * hold data and the query won't get invalid because of an empty array **/ $update_data_profile['user_id'] = $user_id; if(count($update_data_profile)){ $columns = array(); $values = array(); foreach($update_data_profile as $field => $data){ $columns[] = $field; $values[] = $data; } $sql = "insert into profile (" . implode(",",$columns) .") values ('" . implode("','",$values) . "')" ; var_dump($sql); //remove this line,this was only to show what the code was doing /**update**/ mysql_query($sql) or echo mysql_error(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |