Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 381

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T10:21:07+00:00 2024-11-25T10:21:07+00:00

How to Integrate Google Sheets with a PHP Website Form: Step-by-Step Guide

  • 62k
  • Storing form data directly in Google Sheets helps improve data management and collaboration. This integration enables various team members to view and analyse data in real time, without having to deal with sophisticated database queries.

1. Create a Google Sheet

  • Go to Google Sheets.
  • Create a new sheet and name it accordingly, e.g., “Form Submissions.”
  • In the first row, create headers for the data you want to store. For example, if you are collecting name, email, and message, create columns titled Name, Email, and Message.

2. Create a Google Apps Script Web App

  • Go to Extensions > Apps Script.

3. Write the Google Apps Script to Accept Form Data

function doPost(e) {   let ss = SpreadsheetApp.openById("123123asdasd"); // Change "SpreadsheetAppId" to your actual sheet id   let sheet = ss.getSheetByName("Sheet1"); // Change "Sheet1" to your actual sheet name    let data;   try {     data = JSON.parse(e.postData.contents);   } catch (err) {     data = e.parameter;   }    sheet.appendRow([data.name, data.email, data.message]);    return ContentService.createTextOutput("Success").setMimeType(ContentService.MimeType.TEXT); } 
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • function doPost(e)

    • This is a special function in Google Apps Script that is triggered whenever your web app receives an HTTP POST request. The e parameter contains the information sent by the form.
  • let ss = SpreadsheetApp.openById(“123123asdasd”);

    • This line opens the Google Spreadsheet by its unique ID. Replace the ID “123123asdasd” with your own Google Sheet's ID, which you can find in the sheet’s URL.
  • var sheet = ss.getSheetByName(“Sheet1”);

    • This retrieves the specific sheet within the spreadsheet where you want to append the form data. If your sheet has a different name, replace “Sheet1” with your actual sheet name.
  • var data;
    • This variable will store the incoming form data after it is parsed.
  • try { data = JSON.parse(e.postData.contents); } catch (err) { data = e.parameter; }

    • Here, the code attempts to parse the incoming data as JSON, assuming the form sends data as JSON. If parsing fails (meaning the form used a URL-encoded format instead), it falls back to e.parameter, which contains the URL-encoded form data.
    • JSON.parse(e.postData.contents): Attempts to parse the body of the request as JSON.
    • e.parameter: Holds the form data if it was sent in URL-encoded format (as is typical for HTML forms).
  • sheet.appendRow([data.fname, data.email, data.message]);

    • This appends the data from the form to the next available row in the Google Sheet. The data is extracted from the data object, which contains in the form input fields
  • return ContentService.createTextOutput(“Success”).setMimeType(ContentService.MimeType.TEXT);

    • After successfully appending the data to the sheet, this line returns a success message (“Success”) to the client (the website or app that submitted the form).
      • ContentService.createTextOutput(“Success”): Creates a plain text response containing the word “Success”.
      • setMimeType(ContentService.MimeType.TEXT): Sets the MIME type of the response to plain text.

4. Deploy the Script as a Web App

  1. Click on Deploy > Test deployments in the top-right corner of the script editor.
  2. Select Manage deployments, then click on New Deployment.
  3. In the “Select type” dropdown, choose Web app.
  4. Under Execute as, choose Me.
  5. Under Who has access, choose Anyone.
  6. Click Deploy and copy the generated Web App URL and copy that.

5. PHP Code to Submit Form Data to Google Apps Script Web App

Html code:

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Submit Form</title> </head> <body>     <form method="post" action="submit.php">         <label for="name">Name:</label>         <input type="text" name="name" required><br>          <label for="email">Email:</label>         <input type="email" name="email" required><br>          <label for="message">Message:</label>         <textarea name="message" required></textarea><br>          <input type="submit" value="Submit">     </form> </body> </html>  
Enter fullscreen mode Exit fullscreen mode

PHP code:

 <?php if ($_SERVER["REQUEST_METHOD"] == "POST") {     $url = 'YOUR_WEB_APP_URL'; // Replace with your Google Apps Script Web App URL      $postData = array(         'name' => $_POST['name'],         'email' => $_POST['email'],         'message' => $_POST['message'],     );      $ch = curl_init($url);       $postFields = http_build_query($postData);      curl_setopt($ch, CURLOPT_POST, 1); // Send a POST request     curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); // Attach the POST fields     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string      $response = curl_exec($ch);      if ($response === false) {         $error = curl_error($ch);         echo "cURL error: $error";     } else {         echo "Server response: $response";     }      curl_close($ch); } ?> 
Enter fullscreen mode Exit fullscreen mode

htmljavascriptphpwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.