简体   繁体   English

将 php 表中的数据插入我的 mysql 数据库

[英]Insert data from a php table to my mysql database

I would like to ask for support to be able to insert the data I bring into a table and insert it into a table in my mysql database.我想寻求支持,以便能够将我带入的数据插入到表中,并将其插入到我的 mysql 数据库中的表中。

在此处输入图像描述

I have a button that I want to click on to save the data in a mysql table.我有一个按钮,我想单击它以将数据保存在 mysql 表中。

How do I pass the data that is in the table and send it to the database?如何传递表中的数据并将其发送到数据库?

Can I do it using AJAX?我可以使用 AJAX 吗?

Yes - you can save using AJAX.是的 - 您可以使用 AJAX 进行保存。 One possible approach:一种可能的方法:

  1. When a user clicks save, run a loop in javascript to gather the fields of each row into an object, and add it to an array;当用户点击保存时,在 javascript 中运行一个循环,将每一行的字段收集到一个 object 中,并将其添加到一个数组中; a structure like:像这样的结构:
var table_data = [
    {field1:value1, field2:value2, field3: value3...}, // one of these for every row in the table
]

fieldX would be the names of your column headers, and valueX would be the values of those fields. fieldX将是您的列标题的名称,而valueX将是这些字段的值。

  1. Using ajax, post the data to a server-side script.使用 ajax,将数据发布到服务器端脚本。 An example using jQuery:使用 jQuery 的示例:
$ajax.({
    type : 'POST',
    url  : 'script.php',
    data : { 'submit_data' : table_data } 
});
  1. On the server in a file called script.php, receive the POST'ed data, and then run a loop over the data to save each row to the table.在服务器上一个名为 script.php 的文件中,接收 POST 数据,然后对数据运行循环以将每一行保存到表中。 Here's a sparse example, using PHP and mysqli:这是一个稀疏示例,使用 PHP 和 mysqli:
$mysqli = database_connection();
$data = $_POST['submit_data']; //sanitize this!

foreach($data as $row){
    $mysqli->query( "INSERT INTO data_table (field1, field2, field3) VALUES($row['field1'], $row['field2'], $row['field3'])" );
}

Bear in mind the above is very unsafe for a production environment;请记住,以上对于生产环境是非常不安全的; at a minimum, you should use prepared statements and parameter binding to insert the data: https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php至少,您应该使用准备好的语句和参数绑定来插入数据: https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

I hope this gets you going.我希望这能让你继续前进。 GL! GL!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM