Home Backend Development PHP Tutorial Implementation of shopping cart function through php+MySQL+jQuery+Ajax

Implementation of shopping cart function through php+MySQL+jQuery+Ajax

Jun 15, 2018 pm 02:48 PM
html5 jquery

Recommended related mysql video tutorials: "mysql tutorial"

Database structure:


Prepare 3 files:

1.cart.php //Front-end display file

2.cart_ajax.php //Ajax processing Data

3.config.php //Database configuration

1, cart.php

<pre name="code" class="html"><?php

include 'config.php';
$sql = "select * from cart";
$result = mysql_query($sql);
$row = array();
while($rows = mysql_fetch_array($result,MYSQL_ASSOC)){
    $row[] = $rows;
}
//print_r($row);
?>
<!DOCTYPE html>
<html lang="zh-hans">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<table width="" border="1" cellspacing="0" cellpadding="0" align="center">
    <tr>
        <td>商品名称</td>
        <td>商品库存</td>
        <td>商品单价</td>
        <td>购买数量</td>
        <td>小计</td>
        <td>操作</td>
    </tr>
    <!--遍历数据-->
    <?php foreach($row as $key=>$val){?>

    <tr>
        <td><?php echo $val['name'] ?></td>
        <td><?php echo $val['total_quantity'] ?></td>
        <!--商品单价-->
        <td><input type="text" name="price" value="<?php echo $val['price'] ?>"></td>
        <td>
            <button onclick="minusCart(this, '<?php echo $val['id'] ?>')">-</button>
            <!--购买数量-->
            <input type="text" name="num" value="<?php echo $val['num'] ?>" max="<?php echo $val['total_quantity'] ?>" />
            <button onclick="plusCart(this, '<?php echo $val['id'] ?>')">+</button>
        </td>
        <!--小计价格  -->
        <td><input type="text" name="subtotal_price" value="<?php echo $val['price']*$val['num'];?>" onclick="price()"></td>
        <td><button>编辑</button><button>删除</button></td>
    </tr>

    <?php }?>

    <tr>
        <!--总价-->
        <td>总价</td>
        <td colspan="4">0元</td>
    </tr>
</table>
<!--<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js"></script>-->
<script src="jquery-2.1.1.min.js"></script>
<script>
    function setPrice(o) {//设置小计和总价
        var tr = o.closest('tr');
        var ipt = tr.find('input');
        ipt.filter(':last').val(parseInt(o.val()) * parseInt(ipt.eq(0).val(), 10));
        var sum = 0;
        o.closest('tbody').find('input[name="subtotal_price"]').each(function () { sum += parseInt(this.value, 0) || 0; })
            .end().find('td:last').html(sum+'元')
    }
    //减
    function minusCart(_this, id){
        var num_input = $(_this).next('input[name="num"]');
        var num = parseInt(num_input.val());
        num--;
        if(num <= 0){
            return false;
        } else {
            num_input.val(num);
            setPrice(num_input);
            cartNum(num_input, id, num);
        }
    }
    //加
    function plusCart(_this,id){
        //获取购买数量
        var num_input = $(_this).prev('input[name="num"]');
        var num = parseInt(num_input.val());
        var total_quantity = parseInt(num_input.attr('max'));
        if(num >= total_quantity){
            alert('库存不足');
            return false;
        }else {
            //alert(num);
            num = parseInt(num) + 1;
            num_input.val(num);
            setPrice(num_input);
            cartNum(num_input, id, num);
        }
    }

    /**
     * 修改购物车商品数量
     * @param _this
     * @param id
     * @param num
     */
    function cartNum(_this, id, num){
        $.ajax({
            type: 'POST',
            url: 'cart_ajax.php',
            data: {id: id, num: num},
            dataType: 'json',
            success: function (res) {
                if (res.status == 1) {
                    _this.val(num);
                }else{
                    alert(res.info);
                }
            }
        });
    }



</script>
</body>
</html>
Copy after login

2, config.php

<?php
/**
 *email:scenewood@163.com
 *name:郑小木
 */
$server = 'localhost';
$data = 'shopping';
mysql_connect($server,'root','root');
mysql_set_charset('utf8');
mysql_select_db($data);
Copy after login

3 , cart_ajax.php

<?php
/**
 *email:scenewood@163.com
 *name:郑小木
 */
include 'config.php';


//接受cart.php的数据
if ($_POST) {
    $id = $_POST['id'];
    $num = $_POST['num'];
    $retureInfo = array(
        'status' => 0,
        'info' => '修改商品数量失败'
    );
    $sql = "UPDATE `cart` SET num='{$num}' WHERE `id`={$id}";
    mysql_query($sql);
    $row = mysql_affected_rows();
    if ($row == 1) {
        $retureInfo['status'] = 1;
        $retureInfo['info'] = '修改商品数量成功';
    }
    echo json_encode($retureInfo);
}
Copy after login

This article explains how to implement the shopping cart function through php MySQL jQuery Ajax. For more related content, please pay attention to the php Chinese website.

Related recommendations:

How to deploy php mysql apache through linux system Related operations

##Nginx PHP Mysql environment setup under Linux Process explanation

Nginx PHP Mysql environment setup process explanation under Linux

The above is the detailed content of Implementation of shopping cart function through php+MySQL+jQuery+Ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

Nested Table in HTML

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Table Border in HTML

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

HTML margin-left

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

HTML Table Layout

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Moving Text in HTML

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

HTML Ordered List

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

HTML onclick Button

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

HTML Input Placeholder

See all articles