PHP SQL商品更新相关代码

  • Post author:
  • Post category:php


<?php

  include_once('./lib/func.php');
  session_start();
  // 验证用户登录
  if (!$_SESSION['user'] || empty($_SESSION['user'])) {
    msg(0, '用户请先登录, 在进行数据编辑~', 'login.php');
  }

  if (empty($_POST['name'])) {
    msg(0, '非法访问, 请提交表单', 'index.php');
  }

  // 链接数据库
  $connect = mysqlInit('localhost', 'root', '', 'shop');

  // 获取post提交的表单数据并验证字段规则
   $id = $_POST['id'];
   if (empty($id)) {
     msg(0, '参数非法', 'index.php');
   }
   $sql = "SELECT * FROM goods WHERE id='{$id}'";
   $result = mysqli_query($connect, $sql);
   $data = mysqli_fetch_all($result, MYSQLI_ASSOC);
   if(count($data) <= 0) {
     msg(0, '所查询的商品id不存在');
   }

  $name = mysqli_real_escape_string($connect, trim($_POST['name']));
  $nameLength = mb_strlen($name, 'utf-8');
  if ($nameLength <= 0 || $nameLength > 50) {
    mag(0, '商品名称应该在0 ~ 50个字符之间');
  }

  $price = intval(trim($_POST['price']));
  if ($price <= 0 || $price > 999999999) {
    msg(0, '价格应当在0 ~ 999999999之间');
  }

  $des = mysqli_real_escape_string($connect, trim($_POST['des']));
  $desLength = mb_strlen($des, 'utf-8');
  if ($desLength <= 0 || $desLength > 100) {
    msg(0, '画品简介应当在0 ~ 100个字符之间');
  }

  $content = mysqli_real_escape_string($connect, trim($_POST['content']));
  $contentLength = mb_strlen($content, 'utf-8');
  if(empty($contentLength)) {
    msg(0, '画品描述不能为空');
  }

  // 更新数组
  $updateList = array(
    'name' => $name,
    'price' => $price,
    'des' => $des,
    'content' => $content
  );
  // 当用户上传了图片才做处理
  $file = $_FILES['file'];
  if ($file['tmp_name'] && $file['size'] > 0) {
    $pic = uploadFile($file);
    $updateList['pic'] = $pic;
  }

  // 只更新用户修改过的部分
  foreach($updateList as $k => $v) {
    if ($data[0][$k] == $v) {
      unset($updateList[$k]);
    }
  }
  if (empty($updateList)) {
    msg(0, '操作成功', 'edit.php?goodsId='.$id);
  }


  $sqlItem = "";
  foreach($updateList as $k => $v) {
    $sqlItem .= "{$k} = '{$v}',";
  }
  $sqlItem = rtrim($sqlItem, ',');
  var_dump($sqlItem);
  // 更新操作
  $sql = "UPDATE goods SET {$sqlItem} WHERE id={$id} ";
  if (!mysqli_query($connect, $sql)) {
    msg(0, '服务器繁忙, 请稍后在试', 'edit.php?goodsId='.$id);
  }
  msg(1, '插入成功',  'edit.php?goodsId='.$id);

  mysqli_close($connect);
?>



版权声明:本文为weixin_43753747原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。