Navigation Advertising

Next post Previous post

Post content

How to save search queries on Google Custom Search Engine

MySQL

Does anybody out there run a Google Custom Search Engine?

Still wondering how to save your user’s search queries?

If you host yourself your own CSE, and your server can run PHP/MySQL, here is the solution!

First of all, you have to set up a MySQL table where the search terms searched on your Google Custom Search Engines will be saved: to do so, open your favourite MySQL frontend (like PhpMyAdmin), and run this query:

CREATE TABLE `query` (
`id` int(11) NOT NULL auto_increment,
`query` varchar(255) NOT NULL default '',
`datetime` int(11) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM

Done? Well. Now, open the page in which you pasted the Google’s code that displays search results, and add to that page the code that will save data: it grabs search term from the URL:

< ?php
/*-----------------------
First part: db connection
-------------------------*/
$dbhost = "localhost";
$dbname = "mylittledb";
$dbuser = "root";
$dbpass = "password";
$db=mysql_connect($dbhost, $dbuser, $dbpass);
if ($db==FALSE)
die("Error while connecting to MYSQL ".mysql_error());
mysql_select_db($dbname ,$db);
/*------------------------------
Read and save the search query
-------------------------------*/
$querystat = mysql_real_escape_string($_GET['q']);
$datetime = time();
if( ($_SERVER['HTTP_REFERER'] == '') AND ( ($querystat != $_SESSION['prev_search']) OR ( ($datetime - $_SESSION['datetime']) > 60) ) ) {
$insertquery = “INSERT INTO `query` ( `query` , `datetime`) VALUES ( ‘$querystat’ , ‘$datetime’);”;
mysql_query($insertquery, $db);
}
$_SESSION[’datetime’] = $datetime;
$_SESSION[’prev_search’] = $querystat;
?>

That’s all.

This code saves also the time/date of each search, so you can may later analyze searches e.g. per day, per month, or per time period.

Example’d code saves queries only if the referer is blank (i.e. the user did not request the search results page clicking on a link to it, but he has to manually submit the form), and it prevents multiple page refreshes (a minute at least has to pass, or the search query has to be different, before the term is saved into database).

If you don’t want filters, and you want to save right every query, keep just the database connection and the two lines inside the IF statement for the second part.

Bookmark:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • digg
  • del.icio.us
  • blogmarks
  • co.mments
  • NewsVine
  • Furl

Related articles

Other posts filed under MySQL, PHP, Search Engines

Comments and trackbacks

6 comments for “How to save search queries on Google Custom Search Engine” (RSS)

  1. Olaf wrote:

    Hi,

    I use a similar code but check first if there is already a record for this search string, if yes update the count number otherwise insert a new record.

    Olaf

  2. Maurizio Petrone wrote:

    Hi Olaf,
    I used too to increase the value of a counter field, but doing so the time/date/ip/etc information for each query are lost.

    However, it’s fine if you want just to save raw search volumes ;-)

  3. Mike wrote:

    If my result page is results.php Where do I put the the second code to this page.

  4. Maurizio Petrone wrote:

    Mike, you may put it just after the G’le code that shows results: it works for me.



    UPDATE Seems that from yesterday that in CSE, when you run a search, referer url is forwarded *everytime*.
    If you find that no query is saved, try to change this line:
    if( ($_SERVER['HTTP_REFERER'] == '') AND ( ($querystat != $_SESSION['prev_search']) OR ( ($datetime - $_SESSION['datetime']) > 60) ) ) {

    with the following:

    if( ($querystat != $_SESSION['prev_search']) OR ( ($dataora - $_SESSION['dataora']) > 60) ) {
    This will save right every query with - No Care if it was submited manually or generated from a direct link to that search.

    I’m still working-around in my CSE, keep in touch with this issue on Google Groups ;)

  5. Mark wrote:

    Thanks for the code, Maurizio! I used the modified version and it works great….

  6. Alessio wrote:

    Ciao Maurizio
    scusa se scrivo in italiano sul tuo blog.
    Ho installato il tuo script ma ricevo questo errore

    Parse error: syntax error, unexpected T_STRING in /home/alefotoi/domains/odontotecnico.info/public_html/index.html on line 68

    la riga e’ questa

    $insertquery = “INSERT INTO `query` ( `query` , `datetime`) VALUES ( ‘$querystat’ , ‘$datetime’);”;

    Qualche aiuto?

Add your comment:

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

1 Trackbacks / Pings to “How to save search queries on Google Custom Search Engine”

  1. Google blog» Архив блога » Here’s some love for our Custom Search friends

    [...] How to save search queries on Google Custom Search Engine [...]