Resources
In this post I’m going to show how to post to Google Sheets with PHP. We will save data submitted through a form on your website into a Google sheet. I recently worked on a project where the client ran a competition and the entries were saved in a Google sheet. This meant the client could view all the competition entries in one place and not have to crawl through emails and extract data that way. You could store the entries in a database but you would also have to create a ui for the client to view the entries.
First off we’ll create our spreadsheet in Google Sheets. For this example we’ll call it “Website Submissions”. We’ll have four columns name, email, message and subject. These will also be the fields for our form.
Next we’ll create a form for a user to enter information on our website. I’ve used the code from a previous article
<form class="basic-grey" action="validate.php" method="post">
<h1>Contact Form</h1>
<label> Your Name : <input id="name" name="name" type="text" placeholder="Your Full Name" /> </label>
<label> Your Email : <input id="email" name="email" type="email" placeholder="Valid Email Address" /> </label>
<label> Message : <textarea id="message" name="message" placeholder="Your Message to Us"></textarea> </label>
<label> Subject :<select name="selection">
<option value="Job Inquiry">Job Inquiry</option>
<option value="General Question">General Question</option>
</select></label>
<label> <input class="button" name="submit_form" type="submit" value="Send" /> </label>
</form>
In our validate.php
file we start with setting the include path to the Zend library and require Google_Spreadsheet.
/*
* Set Include Path
*/
$clientLibraryPath = "$_SERVER[DOCUMENT_ROOT]/path-to-folder-containing-Zend-library";
set_include_path(get_include_path() . PATH_SEPARATOR . $clientLibraryPath);
/*
* Include Google_Spreadsheet Class
*/
require_once("inc/Google_Spreadsheet.php");
In this next snippet initiate the Google_Spreadsheet class and save the posted data in the spreadsheet.
// insert into google sheets
$u = "[email protected]";
$p = "password";
$ss = new Google_Spreadsheet($u, $p);
// spreadsheet name must match one we created "Website Submissions"
$ss->useSpreadsheet("Website Submissions");
// if not setting worksheet, "Sheet1" is assumed
// $ss->useWorksheet("worksheetName");
$row = array
(
"name" => $_POST['name'],
"email" => $_POST['email'],
"message" => $_POST['message'],
"subject " => $_POST['subject'],
);
if ($ss->addRow($row)) {
header('Location: index.php?msg=success');
exit;
} else {
header('Location: index.php?msg=failure');
exit;
}
You may need to change permissions for less secure apps on your google account for this to work.