这里要注意,提交的数据必须为json格式的字符串,不能直接提交对象或者数组,不然sql.php是很难直接处理js对象的。
//mock.php 接上面//JSON.parse(jsonstr); //可以将json字符串转换成json对象//JSON.stringify(jsonobj); //可以将json对象转换成json对符串data=JSON.stringify(login.list); $.post('/sql.php',{comments:data},function(res){ //以post方式提交数据 document.write(res) //打印返回值到页面,不写也可以})</script>下面写sql.php<?phpheader('Content-type:text/html;charset=utf8');//连接数据库define('DB_USER','root');define('DB_HOST','localhost');const DB_PASS='root';const DB_NAME='root';$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('数据库连接失败');mysqli_query($con,'set names utf8');//封装sql执行函数function xiu_execute($sql){ global $con; // 获取数据库连接的全局变量 $query = mysqli_query($con, $sql); //执行数据库 *** 作sql语句 if (!$query) { // 查询失败 return false; } // mysqli_affected_rows() 函数返回前一次 MySQL *** 作(SELECT、INSERT、UPDATE、REPLACE、DELETE)所影响的记录行数。
return mysqli_affected_rows($con);}/** * PHP json_encode() 用于对变量进行 JSON 编码,该函数如果执行成功返回 JSON 数据,否则返回 FALSE 。
* PHP json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]]) * 函数用于对 JSON 格式的字符串进行解码,并转换为 PHP 变量,assoc: 当该参数为 TRUE 时,将返回数组,FALSE 时返回对象。
*/if(!empty($_POST['comments'])){ //判断接收的数据是否为空 $comments=json_decode($_POST['comments'],true) ; //将接收到的json字符串数据解码为关联数组 $sql="insert into comments values"; //定义初始查询语句 foreach($comments as $comment){ //遍历解码后的关联数组,获取每一项每个字段的数据 $author=$comment['author']; $email=$comment['email']; $created=$comment['created']; $content=$comment['content']; $status=$comment['status']; $post_id=$comment['post_id']; $parent_id=$comment['parent_id']; // 将得到的数据拼接,插入多条sql语句 $sql.="(null,'{$author}','{$email}','{$created}','{$content}','{$status}',{$post_id},{$parent_id}),"; } $sql=substr($sql,0,-1).";"; //将拼接完后的最后一个逗号删除并加上冒号 execute($sql); //执行插入 *** 作 echo $sql; //返回拼接后的字符串,用以调试是否出错!将这两个文件放在php服务器根目录上,访问mock.php,即可批量插入数据,如果要插入更多数据,只需要将‘list|5’中的5修改为你想要插入的数据条数即可!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)