duanchu9914 2018-09-07 09:54
浏览 66
已采纳

更新记录:如何检查新文件是否已上传PHP

I am learning PHP, so forgive me if my question is somewhat silly.

I have created a form to update records in my db, which includes changing your name, age and image. When I update a record without changing the image it deletes the image (base64 string) from the updated row.

How can I check if an image has been changed or not, and if not: keep the present one unchanged or put into other words, not update that specific field. here is my php script for the update:

if( !is_null( $db ) && array_key_exists( 'edit_person', $_POST ) ):
  $pn = filter_var( trim( $_POST['name'] ), FILTER_SANITIZE_STRING );
  $n = filter_var( trim($_POST['age'] ), FILTER_SANITIZE_STRING );
  // check if another image has been uploaded
  $img = filter_var( trim($_POST['img'] ), FILTER_SANITIZE_STRING );
  // if not: don't update img
  $id = filter_var( trim ( $_POST['id'] ), FILTER_SANITIZE_NUMBER_INT );
  update_person( $db, $id, $img, $n, $pn ); 
 endif;

the update_person function:

   function update_person( &$db, $id, $img, $age, $name ){ 
   if( is_null( $db ) ) return '';
   $sql = "
    UPDATE
      xxx
    SET
      xxx.name = :name,
      xxx.age = :age,
      xxx.img = :img
    WHERE
      xxx.id = :id
    ";
  $vraag = $db->prepare( $sql );
  $vraag->bindValue( ':name', $name, PDO::PARAM_STR );
  $vraag->bindValue( ':age', $age, PDO::PARAM_STR );
  $vraag->bindValue( ':img', $img, PDO::PARAM_STR ); 
  $vraag->bindValue( ':id', $id, PDO::PARAM_INT );
  $vraag->execute();
}

Any help is very much appreciated!

  • 写回答

1条回答 默认 最新

  • doupin1073 2018-09-07 10:26
    关注

    Try the below code. If the $img variable is not set, do not update the image column in table

    if( !is_null( $db ) && array_key_exists( 'edit_person', $_POST ) ):
      $pn = filter_var( trim( $_POST['name'] ), FILTER_SANITIZE_STRING );
      $n = filter_var( trim($_POST['age'] ), FILTER_SANITIZE_STRING );
      // check if another image has been uploaded
      $img = filter_var( trim($_POST['img'] ), FILTER_SANITIZE_STRING );
      // if not: don't update img      
      $id = filter_var( trim ( $_POST['id'] ), FILTER_SANITIZE_NUMBER_INT );
    
      if(!empty($img) && $img != '') :
        update_person( $db, $id, $n, $pn ); 
      else:
        update_person( $db, $id, $img, $n, $pn ); 
      endif;
    endif;
    

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了