dongshen4129 2014-05-14 10:08
浏览 8
已采纳

从表单中编写PHP更新代码

Like the title itself is telling i would like to write soms PHP update mysql code into a shorter way

Here is an example block of the php code:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

  $getid = $_SESSION['id']

  if (empty($_POST['name']) {
  $name = ' ',
  }

  if (empty($_POST['firstname']) {
  $firstname = ' ',
  }

  if (empty($_POST['address']) {
  $address = ' ',
  }

  $upregstmt = $dbh->prepare("UPDATE contacts SET c_firstname = ?, c_name = ?, c_address = ? WHERE c_id = ?");  
  $upregstmt->bindParam(1, $firstname);
  $upregstmt->bindParam(1, $name);
  $upregstmt->bindParam(1, $address);
  $upregstmt->bindParam(1, $getid);
  $upregstmt->execute();


}

I have a much larger form where not everything will be filled in and must stay empty so i have to at an empty variable in that case.

Question: isn't there a walk around for this (a parameter you can send with your query for example that it doesn't give me an empty variable error?) and cant the other code been written smaller?

  • 写回答

1条回答 默认 最新

  • du8791069 2014-05-14 10:12
    关注

    You can shorten it a bit doing this:

    $exludeArray = array("submit");
    foreach ($_POST as $key => $value) {
        if (!in_array($key, $excludeArray))
            $upregstmt->bindParam(1, (empty($value) ? " " : $value));
    }
    

    It loops through your $_POST global, exclude things you dont want to add, such as the submit button.

    It is untested, but should give you an idea on how to approach this.

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

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答