点击更改数据库图片?

时间:2019-05-01 21:12:02

标签: php jquery twitter-bootstrap phpgrid

我要在两天内完成作业。我已经尝试这样做4天了,但是我无法完成这项工作,因此我想请教您一些建议。我尝试尝试的所有方法都无法满足我的需求。我正在做一个商店,并且已经进行了登录注册,产品展示,但是我却一无所获。

当用户进入产品页面时,他/她可以选择产品的颜色。例如,如果用户想要一个金色的iPhone,然后单击黑色iPhone的侧面,则该侧面将变成金色。图片应存储在MySQL数据库中,这样,当用户单击“立即订购”时,图片上应显示“ Gold iPhone”。

代码:https://codeshare.io/UbKVU

我尝试至少做出回声,以便可以将其保存到数据库中。..但是没什么。(我知道它的愚蠢想法,但是...)

1 个答案:

答案 0 :(得分:0)

好吧,这是使用json数据管理购物车的客户端部分(您可以通过php和mysql表创建该数据。我还将介绍PHP / SQL Schema方面的内容。

这是codepen的工作示例:https://codepen.io/xonosnet/pen/xeoYLz

var checkout = {
  items: [],
  total: 0.00
};

var phones = [
    {
      title: 'iPhone 7',
      model: 'MHCPL6',
      price: 625.22,
      selectedColor: '',
      colors: {
        'White' : '255,255,255',
        'Black' : '0,0,0',
        'Gray'  : '127,127,127',
        'Pink'  : '215,191,191'
      },
      images: {
        'White' : 'https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/image/AppleInc/aos/published/images/M/QG/MQGX2/MQGX2?wid=2000&hei=2000&fmt=jpeg&qlt=95&op_usm=0.5,0.5&.v=1516399367562',
        'Black' : 'https://www.att.com/shopcms/media/att/2017/shop/360s/8510273/6166B-1.jpg',
        'Gray'  : 'https://cloud.istyles.com/images/Skins/OSI7P/800/OSI7P-SS-GRY.jpg',
        'Pink'  : 'https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/image/AppleInc/aos/published/images/M/QH/MQH22/MQH22?wid=2000&hei=2000&fmt=jpeg&qlt=95&op_usm=0.5,0.5&.v=1516399708457'
      }
    },
      {
      title: 'iPhone 8',
      model: 'DDCNT7',
      price: 785.22,
      selectedColor: '',
      colors: {
        'White' : '255,255,255',
        'Black' : '0,0,0',
        'Gray'  : '127,127,127',
        'Red'  : '225,0,0'
      },
      images: {
        'White' : 'https://s3.envato.com/files/253291200/preview/preview1.jpg',
        'Black' : 'https://img.tvc-mall.com/uploads/details/101112311A-1.jpg',
        'Gray'  : 'https://cloud.istyles.com/images/Skins/OSI7P/800/OSI7P-SS-GRY.jpg',
        'Red'  : 'https://img.tvc-mall.com/uploads/details/101112364C-1.jpg'
      }
    }
  ];

  //Do a post frequest to pull this data out of the DB
  //var phones = get_phones();
  
  $.each(phones, function(index,phone) {
    var phoneColors = get_phone_colors(index); 
    const htmlData = [
      '<div class="phone" data-index="'+index+'">',
      ' <h2>'+phone.title+' <small>('+phone.model+')</small> <span class="price">$'+phone.price+'</span></h2>',
      ' <h4>Choose a color:</h4>',
      ' <div class="color-picker-ctn">',
      '   <div class="color-picker">'+phoneColors.colors+'</div>',
      '   <div class="phone-image" data-model="'+phone.model+'">'+phoneColors.default+'</div>',
      ' </div>',
      ' <button class="add-cart-btn">Add to Cart</button>',
      '</div>'
    ];
    $('.container').append(htmlData.join(''));
  });

function get_phone_colors(i) {
  var p = phones[i],
      data = {
        colors:'',
        default:''
      },
      pass = 0;
  console.log(p);
  $.each(p.colors, function(index,c) {
    var htmlOutput = '<div class="color '+(pass == 0 ? 'color-selected':'')+'" data-key="'+index+'" data-img="'+p.images[index]+'" data-model="'+p.model+'" data-index="'+i+'" style="background-color:rgb('+c+');"></div>';
    console.log('IMG INDEX: '+i);
    data.colors = data.colors+htmlOutput;
    if(pass == 0) {
      phones[i].selectedColor = index;
      data.default = '<img src="'+p.images[index]+'"/>'
    }
    pass = pass+1; 
  });
  return data;
}

function get_phones(phonedata = []) {
  $.post('your_file.php', {get_phones:true}, function(data) {
         phonedata = data;
  },'json');
  return phonedata;
}

$(document).on('click', '.color', function() {
  var model = $(this).data('model'),
      key = $(this).data('key'),
      img = $(this).data('img'),
      index = $(this).closest('.phone').data('index'),
      model = phones[index].model;
  console.log(img);
  console.log("INDEX: "+index);
  phones[index].selectedColor = key;
  $('.color-selected').toggleClass('color-selected');
  $(this).addClass('color-selected');
  $('.phone-image[data-model="'+model+'"]').empty().append('<img src="'+img+'"/>');
});
 

$(document).on('click', '.add-cart-btn', function() {
  var phone = phones[$(this).closest('.phone').data('index')];
  checkout.items.push(phone);
  checkout.total = checkout.total+phone.price;
  
  update_cart();
}); 

var checkout = {
  items: [],
  total: 0.00
};

function update_cart() {
  var htmlOutput = [];
  checkout.total = 0.00;
  if(checkout.items.length > 0) {
    $.each(checkout.items, function(k,v) {
      const output = [
        '<div class="checkout-item">',
        ' <span>'+v.selectedColor+' '+v.title+' ('+v.model+')</span>',
        ' <span>$'+v.price+'</span>',
        '</div>'
      ];
      htmlOutput.push(output.join(''));
      checkout.total = checkout.total+v.price;
    });
    $('.cart').empty().append(htmlOutput.join(''));
    $('.cart').append('<h4>Total: $'+checkout.total.toFixed(2)+'</h4>');
  } else {
    checkout.total = 0.00;
  }
}
.cart {
  display:inline-block;
  width:300px;
  pading:50px;
  vertical-align:top;
}

.container {
  display:inline-block;
  width:auto;
  background-color:rgb(255,255,255); 
  pading:25px;
}
small {
  font-size:14pt;
  font-weight:normal;
}
.price {
  float:right;
}
.phone {
  display:inline-block;
  width:400px;
  height:500px;
  background-color:#FFF;
  border-radius:10px;
  border:2px solid #CCC;
  padding:10px;
  margin:25px; 
}
.color-picker-ctn {
  display:block; 
  width:100%;
  verticle-align:top;
  valign:top;
  background-color:#FFF;
}
.color-picker {
  vertical-align:top;
  display:inline-block;
  width:25%;
}
.phone-image {
  vertical-align:top;
  display:inline-block;
  width:70%;
  border-raidus:15px;
  overflow:hidden;
  background-color:#FFF;
}
.phone-image img {
  border-raidus:15px;
}

.color {
  display:block;
  width:80%;
  height:55px;
  border-radius:5px;
  margin-bottom:5px;
  vertical-align:top;
  valign:top;
  text-align:center;
  border:4px solid rgb(0,0,0,.25);
  transition:all ease 250ms;
}

.color:hover {
  cursor:pointer;
  transition:all ease 250ms;
  border:4px solid rgb(255,0,0);
}
.color-selected {
  border:4px solid rgb(0,255,0)!important;
}


.phone-image img {
  display:block;
  width:100%;
  height:auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cart">
  <p>No items in cart yet.</P>
</div>

<div class="container">
   
  
  
</div>

这是有关数据库外观的简单表模式。

CREATE TABLE `products` (
  `product_id` int(12) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `model` varchar(50) DEFAULT NULL,
  `price` decimal(6,2) DEFAULT '0.00',
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `product_colors` (
  `option_id` int(12) NOT NULL AUTO_INCREMENT,
  `product_id` int(12) NOT NULL,
  `color_name` varchar(50) NOT NULL,
  `color_rgb` varchar(11) DEFAULT '255,255,255',
  `color_img` text,
  `additional_cost` decimal(6,2) DEFAULT '0.00',
  PRIMARY KEY (`option_id`),
  KEY `product_id` (`product_id`),
  CONSTRAINT `product_colors_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Aaa,最后,这是处理PHP方面的一种简单而又肮脏的方法。我没有提供有关如何建立数据库连接的说明(在此示例中,我通过$ conn进行调用。如果不知道如何查找PDO Mysql连接。

<?php
    if(isset($_POST['get_phones']) {
        $json = get_phones();
        echo json_encode($json, JSON_PRETTY_PRINT);
    }

    function get_phones($return = array()) {
        global $conn; //Your mysql connection object (using PDO)
        $query = 'SELECT p.product_id, p.title, p.model, p.price FROM products as p';
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $rc = $stmt->rowCount();
        if($rc > 0) {
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $colors = get_product_colors($row['product_id']);
                $return[] = $row;
                $return['colors'] = $colors['colors'];
                $return['img'] = $colors['img'];
            }
        }
        return $return;
    }

    function get_product_colors($pid, $return = array('colors'=>array(), 'img'=>array())) {
        global $conn;
        $query = 'SELECT p.option_id, p.color_name, p.color_rgb, p.color_img FROM product_colors as p WHERE p.product_id = '.$pid;
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $rc = $stmt->rowCount();
        if($rc > 0) {
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $return['colors'][$row['color_name']] = $row['color_rgb'];
                $return['img'][$row['color_name']] = $row['color_img'];
            }
        }
        return $return;
    }
?>