php用jquery添加多条数据,用json存储mysql

Posted

技术标签:

【中文标题】php用jquery添加多条数据,用json存储mysql【英文标题】:Php add multiple data with jquery and store mysql with json 【发布时间】:2021-05-22 17:15:15 【问题描述】:

您好,我有一个小型电子商务应用程序。 我想在单击加号按钮时添加新的 td 并使用数组发布所有数据 我想将此尺寸与 json 一起存储在我的产品表中

product screen

我的餐桌详情是这样的;

 CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `sizes` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`sizes`)),
  `created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我该怎么做?我的代码;

<div class="container">
    <div class="row justify-content-center">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
            <div class="card">
                <div class="card-header">Add Product</div>
                <div class="card-body">
                    <form action="<?=baseURL?>/add.php" method="POST">
                      <div class="mb-3">
                        <label for="title" class="form-label">Title</label>
                        <input type="text" class="form-control" id="title" name="title" required>
                      </div>
                      
                      <div class="mb-3">
                        <table class="table">
                          <thead>
                            <tr>
                              <th scope="col">Size</th>
                              <th scope="col"></th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr>
                              <td><input type="text" class="form-control" id="size" placeholder="42" name="size"></td>
                              <td><a class="btn btn-sm btn-success" id="addSize" name="addSize">+</td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                      <button type="submit" class="btn btn-sm btn-primary">Add</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

jQuery 脚本

<script>
        $( document ).ready(function() 
            $( "#addSize" ).click(function() 
              
            );
        );
    </script>

这是我的 php 代码

$title  = $_POST['title'];

$sizes  = json_encode($_POST['sizes']);

$stmt = $pdo->prepare("INSERT INTO products (title,sizes) VALUES (?, ?)");
$stmt->execute(array($title,$sizes));
$stmt = null;

header('location:'.baseURL);

谢谢。

【问题讨论】:

【参考方案1】:

您好,请查看link,了解如何在点击时添加一行

<html>
<head>
    <title>Table Example</title>
    <script type="text/javascript">
        function addField (argument) 
            var myTable = document.getElementById("myTable");
            var currentIndex = myTable.rows.length;
            var currentRow = myTable.insertRow(-1);

            var linksBox = document.createElement("input");
            linksBox.setAttribute("name", "links" + currentIndex);

            var keywordsBox = document.createElement("input");
            keywordsBox.setAttribute("name", "keywords" + currentIndex);

            var violationsBox = document.createElement("input");
            violationsBox.setAttribute("name", "violationtype" + currentIndex);

            var addRowBox = document.createElement("input");
            addRowBox.setAttribute("type", "button");
            addRowBox.setAttribute("value", "Add another line");
            addRowBox.setAttribute("onclick", "addField();");
            addRowBox.setAttribute("class", "button");

            var currentCell = currentRow.insertCell(-1);
            currentCell.appendChild(linksBox);

            currentCell = currentRow.insertCell(-1);
            currentCell.appendChild(keywordsBox);

            currentCell = currentRow.insertCell(-1);
            currentCell.appendChild(violationsBox);

            currentCell = currentRow.insertCell(-1);
            currentCell.appendChild(addRowBox);
        
    </script>
</head>
<body>
    <table id="myTable">
        <tr>
            <td><input type="text" name="links"></td>
            <td><input type="text" name="keywords"></td>
            <td><input type="text" name="violationtype"></td>
            <td><input type="button" class="button" value="Add another line" onclick="addField();"></td>
        </tr>
    </table>
</body>
</html>

【讨论】:

【参考方案2】:

HTML 表单

<form>
    <div class="mb-3">
      <label for="title" class="form-label">Title</label>
      <input type="text" class="form-control" id="title" name="title" required>
    </div>
    <div class="mb-3">
        <label for="title" class="form-label">Size</label>
        <input type="text" class="form-control" id="size" name="size" required>
    </div>
    
    <div class="mb-3">
      <table class="table">
        <thead>
          <tr>
            <th scope="col">Title</th>
            <th scope="col">Size</th>
          </tr>
        </thead>
        <tbody>
          
        </tbody>
      </table>
    </div>
    <button type="button" class="btn btn-sm btn-primary">Add</button>
</form>

JS

<script>
    $( document ).ready(function() 
       $('form>button').click(function() 
           var form = document.querySelector('form');
           var elements = form.querySelectorAll('input[type="text"]');
           let data = [];
           elements.forEach((element) =>  data[element.name] = element.value);
           add_to_tbl(data);
           post(data);
        );
     );
     function post(data)
         data = Object.assign(, data)
         $.post('/*To PHP file or url*/',data, (res)=>
                    console.log(res);
         );
      ;
      function add_to_tbl(arr) 
          let tr = $('<tr/>');
          for (const key in arr) 
              if (Object.hasOwnProperty.call(arr, key)) 
                  tr.append($('<td/>').text(arr[key]));
               
           
           $('.table').find('tbody').append(tr); //change id to your table id
        ;
 </script>

PHP 文件

<?php 
if(isset($_POST))
    $title  = $_POST['title'];
    $sizes  = json_encode($_POST['size']);
    $stmt = $pdo->prepare("INSERT INTO products (title,sizes) VALUES (?, ?)");
    $stmt->execute(array($title,$sizes));
    if($stmt)
        echo json_encode(['status'=>'200']);
    else
        echo json_encode(['status'=>'400']);
    

else
    echo json_encode(['status'=>'404']);

?>

$('form>button').click(() => 
            var form = document.querySelector('form');
            var elements = form.querySelectorAll('input[type="text"]');
            let data = [];
            elements.forEach((element) => 
                data[element.name] = element.value;
            );
            add_list(data);
            // post(data);
        );

        function add_list(arr) 
            let tr = $('<tr/>');
            for (const key in arr) 
                if (Object.hasOwnProperty.call(arr, key)) 
                    tr.append($('<td/>').text(arr[key]));
                
            
            $('.table').find('tbody').append(tr);
        ;
        function post(data)
            let url = '';
            data = Object.assign(, data)
            $.post(url,data, (res)=>
            );
        ;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
    <div class="row justify-content-center">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
            <div class="card">
                <div class="card-header">Add Product</div>
                <div class="card-body">
<form>
        <div class="mb-3">
          <label for="title" class="form-label">Title</label>
          <input type="text" class="form-control" id="title" name="title" required>
        </div>
        <div class="mb-3">
            <label for="title" class="form-label">Size</label>
            <input type="text" class="form-control" id="size" name="size" required>
        </div>
        
        <div class="mb-3">
          <table class="table">
            <thead>
              <tr>
                <th scope="col">Title</th>
                <th scope="col">Size</th>
              </tr>
            </thead>
            <tbody>
              
            </tbody>
          </table>
        </div>
        <button type="button" class="btn btn-sm btn-primary">Add</button>
      </form></div></div></div></div></div></div>

【讨论】:

以上是关于php用jquery添加多条数据,用json存储mysql的主要内容,如果未能解决你的问题,请参考以下文章

用 JQuery/PHP 解析嵌套的 JSON 字符串对象?

瀑布流

用insert into 怎么添加多条记录

jQuery使用cookie与json简单实现购物车功能

使用 jQuery、PHP 和 MySQL 为单选按钮加载 JSON 数据

使用 jQuery、PHP 和 MySQL 为单选按钮加载 JSON 数据