PHP实现批量提交表单数据至Google Sheets替代数据库存储
替换数据库存储为Google Sheets批量提交的PHP实现
第一步:配置Google Sheets接收脚本
先在目标Google Sheets中打开「扩展程序」→「Apps Script」,创建新脚本并替换为以下代码,用于接收PHP发送的POST数据并追加到表格:
function doPost(e) { const data = e.parameter; const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // 按字段顺序追加一行数据(对应first_name, last_name, Category) sheet.appendRow([data.first_name, data.last_name, data.Category]); return ContentService.createTextOutput(JSON.stringify({status: "success"})) .setMimeType(ContentService.MimeType.JSON); }
完成后点击「部署」→「新部署」,选择「Web应用」:
- 执行权限设为「我」
- 访问权限根据需求选择(如选「任何人,甚至匿名」)
部署完成后复制生成的Web应用URL,后续PHP代码会用到。
第二步:替换原数据库插入的PHP代码
将原insert.php替换为以下代码,完全保留原循环处理逻辑,仅将数据库插入操作改为向Google Sheets脚本提交数据:
<?php // 替换为你的Google Sheets Web应用URL $google_script_url = "你的Web应用部署URL"; // 循环处理每组提交的数据,和原数据库插入逻辑一致 for($count = 0; $count < count($_POST['hidden_first_name']); $count++) { // 组装当前组的字段数据 $post_data = array( 'first_name' => $_POST['hidden_first_name'][$count], 'last_name' => $_POST['hidden_last_name'][$count], 'Category' => $_POST['hidden_Category'][$count] ); // 初始化CURL请求 $ch = curl_init($google_script_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data)); // 执行请求并处理响应 $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 可选:记录提交错误 if($http_code !== 200 || strpos($response, '"success"') === false) { error_log("第".($count+1)."组数据提交失败:".$response); } curl_close($ch); } // 可选:向前端返回提交结果 echo "数据提交完成"; ?>
性能优化方案(可选)
如果批量数据量较大,可改为一次性打包发送所有数据,减少HTTP请求次数:
优化后的Google Apps Script:
function doPost(e) { const data = JSON.parse(e.postData.contents); const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // 批量追加多行数据 sheet.getRange(sheet.getLastRow()+1, 1, data.length, 3).setValues(data); return ContentService.createTextOutput(JSON.stringify({status: "success"})) .setMimeType(ContentService.MimeType.JSON); }
优化后的PHP代码:
<?php $google_script_url = "你的Web应用部署URL"; $batch_data = array(); // 先组装所有数据组 for($count = 0; $count < count($_POST['hidden_first_name']); $count++) { $batch_data[] = array( $_POST['hidden_first_name'][$count], $_POST['hidden_last_name'][$count], $_POST['hidden_Category'][$count] ); } // 一次性发送批量数据 $ch = curl_init($google_script_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($batch_data)); $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if($http_code !== 200 || strpos($response, '"success"') === false) { error_log("批量数据提交失败:".$response); } curl_close($ch); echo "数据提交完成"; ?>
内容的提问来源于stack exchange,提问作者Sai rajesh
相关产品推荐
相关产品推荐

