dongpiao8821 2019-07-04 10:55
浏览 106
已采纳

foreach循环获取和处理表​​单数据的问题

I have a form that users can fill in with profile information, all form fields are optional (not required).

My issue is i am trying to go through all form fields and any form fields that are empty assign the value NULL and for form fields that aren't empty assign what user put in form.

Rather than multiple if statements i thought a foreach would be easier and mean cleaner code, but it's the foreach and if statement within the foreach loop that's causing my issue which i do not know how to resolve.

I have not included all the code as don't think it's needed for my issue.

// fetch form data
$formdata       = filter_input_array(INPUT_POST);

// assign session to variables
$user_uid       = $_SESSION['user_uid'];
$user_login     = $_SESSION['user_login'];

foreach ($formdata as $data){
if (empty($data)) {
$formdata = NULL;
}
}

$url = $formdata['url'];
$facebook = $formdata['facebook'];
$twitter = $formdata['twitter'];
$instagram = $formdata['instagram'];
$youtube = $formdata['youtube'];

// connect to database
$dbh = sql_con();

// process to db
$stmt = $dbh->prepare('
UPDATE
users_profiles
INNER JOIN
users
ON
users_profiles.user_uid = users.user_uid
SET
user_url =  :user_url,
user_facebook = :user_facebook,
user_twitter = :user_twitter,
user_instagram = :user_instagram,
user_youtube =  :user_youtube
WHERE
users_profiles.user_uid = :user_uid
AND
users.user_login = :user_login
');

// execute query
$stmt->execute(
array(
':user_url'       => $url,
':user_facebook'  => $facebook,
':user_twitter'   => $twitter,
':user_instagram' => $instagram,
':user_youtube'   => $youtube,
':user_uid'       => $user_uid,
':user_login'     => $user_login
));

If i submit form without filling any form fields, database entry for user gets updated with NULL as i want but if i fill in some or any form field and submit the information i provided in form, still shows NULL in database and does not update with what user entered in form.

i expect form fields that weren't filled in to be assigned value NULL and fields that were filled in to be assigned what user put in form then be updated in database.

Thank you for any help.

  • 写回答

2条回答 默认 最新

  • douchun6221 2019-07-04 11:01
    关注
    $formdata = NULL;
    

    You don’t want to set the complete $formdata array to NULL, but only the current entry:

    foreach ($formdata as $key => $data) {
      if (empty($data)) {
        $formdata[$key] = NULL;
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条