Search code examples
phpmysqlyamlgoogle-cloud-sql

Redirect not working with Cloud SQL


I'm new to coding. The php code generated by my offline software works well with the localhost and mysql. But once its linked to cloud sql of Google App Engine Standard Environment, the php form is not redirecting to the success page. Though with the cloud sql, form data is successfully submitted but then a blank screen appears with no change in url. While with localhost, the success page is appearing after the form gets submitted. To adapt the code for GAE cloud sql, I've inserted $mysql_port and $mysql_Socket variables manually, those are not there in the original code that worked on localhost.

The code is :-

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['formid']) && $_POST['formid'] == 'My-Form-Name')
{
   $success_url = './success-page.html';
   $error_url = './error-page.html';
   $error = '';
   $mysql_server = null;
   $mysql_database = 'My-DB';
   $mysql_table = 'My-Table';
   $mysql_username = 'My-Username';
   $mysql_password = 'My-Password';
   $mysql_port = null;
   $mysql_socket = '/cloudsql/CloudSql-Instance-Connection-Name';
   $eol = "\n";
   $db = mysqli_connect($mysql_server, $mysql_username, $mysql_password, $mysql_database, $mysql_port, $mysql_socket) or die('Failed to connect to database server!<br>'.mysqli_error($db));
   mysqli_set_charset($db, 'utf8');
   mysqli_query($db, "CREATE DATABASE IF NOT EXISTS $mysql_database");
   mysqli_select_db($db, $mysql_database) or die('Failed to select database<br>'.mysqli_error($db));
   mysqli_query($db, "CREATE TABLE IF NOT EXISTS $mysql_table (ID int(9) NOT NULL auto_increment, `DATESTAMP` DATE, `TIME` VARCHAR(8), `IP` VARCHAR(15), `BROWSER` TINYTEXT, PRIMARY KEY (id))");
   foreach($form_data as $name=>$value)
   {
      mysqli_query($db ,"ALTER TABLE $mysql_table ADD $name VARCHAR(255)");
   }
   mysqli_query($db, "INSERT INTO $mysql_table (`DATESTAMP`, `TIME`, `IP`, `BROWSER`, `REFERER`)
                VALUES ('".date("Y-m-d")."',
                '".date("G:i:s")."',
                '".$_SERVER['REMOTE_ADDR']."',
                '".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."',
                '".$_SERVER['HTTP_USER_AGENT']."')")or die('Failed to insert data into table!<br>'.mysqli_error($db)); 
   $id = mysqli_insert_id($db);
   foreach($form_data as $name=>$value)
   {
      mysqli_query($db, "UPDATE $mysql_table SET $name='".mysqli_real_escape_string($db, $value)."' WHERE ID=$id") or die('Failed to update table!<br>'.mysqli_error($db));
   }
   mysqli_close($db);
   header('Location: '.$success_url);
   exit;
}

Success and Error pages are internal pages of the project. App yaml has following handler:

# TO serve static
- url: /(.*\.(html$|css$|js$|svg$|))
  static_files: \1
  upload: (.*\.(html$|css$|js$|svg$))
  application_readable: true


# to serve all php scripts
- url: /(.+\.php)$
  script: \1

How to successfully redirect to success-page.html once the form is submitted with cloud sql? Also, could the success page be .php page or it must be .html page?

After the first help below, it has been found that either the Redirect or the Cloud SQL work at a time. If we remove cloud sql part the Redirect works and if we ignore the Redirect part Cloud SQL successfully puts the data into table but then doesn't redirect. Here I'm specifically naming Cloud SQL because Redirect is working with MySQL on localhost. Please help further on how to redirect a php page with cloud sql form.

Thank you in advance.


Solution

  • Blank page means, that php encountered an runtime error. This could be in your case multiple things:

    • missing SQL rights to create the table
    • missing sql rights to alter an table
    • missing sql rights to insert / update
    • mysqli is not loaded on your online website
    • etc.

    Also, this line should produce an syntax error:

    header('Location: './$success_url);
    

    It should be this:

    header('Location: /'.$success_url);
    

    Or it could also be like this (as seem to like double quotes style):

    header("Location: /$success_url");
    

    To exactly figure out, what went wrong, you have two possibilities:

    • turn on show errors in php.ini
    • look at your error log at your server

    You may also not need the leading slash in your redirect header command.

    Edit: Due to comments below, the questioner needs some additional help to get this issue solved:

    1. Try not to create the database schema each time you open a connection to it. Do this task externally and assume in your script, that the database is already there. Most providers do not support the creation of a database. You mostly have to do this over an web interface, that is served to you by your provider. So, in your case Google's Cloud SQL.
    2. Try not to alter the table each time you use it. That doesn't make sense. I think you have the same HTML form each time. So, it would be better to create columns for all HTML form fields once. Otherwise you could used a serialized form of HTML form data representation (e. g. PHP's serialize command, or for better readability and usage in other languages use json_encode).