PHP registration form

Hi All,
I am currently undertaking a web development project and require some help!

I am coding a simple registration form which I use to connect to a MySQL database and insert all the details in. The registration form is set up and works fine but when I submit the form I get a 500 error saying the registration action script could not be displayed.

The code for both pages is as below:

Form:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>The Gunners Club Crosby - Register</title>
<link href="../css/common.css" rel="stylesheet" type="text/css">
<link href="../css/contact.css" rel="stylesheet" type="text/css">
</head>

<body>

<div class="container">
  <div class="header">
  <a href="#"><img src="../img/logo.png" alt="The gunners regiment logo" id="logo"/></a> 
  <h1>The Gunners Club</h1>
  <div class="userpanel">
    <a href="./login.php">Login</a>
	<a href="./register.php">Register</a>
  </div>
  </div>
  <div class="topnav">
  <ul>
      <li><a href="../index.php">Home</a></li>
	  <li><a href="./history.php">History</a></li>
      <li><a href="./findus.php">Find Us</a></li>
	  <li><a href="./contact.php">Contact Us</a></li>
      <li><a href="./members.php">Members Area</a></li>
	</ul>
  </div>
  <div class="rightbar">
    <ul class="nav">
	<li>Announcement 1 - This is the most recent announcement on the site and will be pulled from a database.</li>
	<li>Announcement 2 - This is the second most recent announcement on the site and will be pulled from a database.</li>
	<li>Announcement 3 - This is the third most recent announcement on the site and will be pulled from a database.</li>
	<li>Announcement 4 - This is the forth most recent announcement on the site and will be pulled from a database.</li>
	<li>Announcement 5 - This is the fifth most recent announcement on the site and will be pulled from a database.</li>
	<li>Announcement 6 - This is the sixth most recent announcement on the site and will be pulled from a database.</li>
    </ul>
    </div>
	<div class="content">
	<h1>Register as an Applicant</h1>
    <form id="register" name="register" method="post" action="../process/register.php" autocomplete="on">
	<label>Title: </label><select name="title" id="title"><option value="Mr.">Mr.</option><option value="Dr.">Dr.</option><option value="Prof.">Prof.</option></select>
	<label>First name: </label><input type="text" name="firstname" id="firstname" autofocus required><br>
	<label>Last name: </label><input type="text" name="lastname" id="lastname" required><br>
	<label>Date of Birth: </label><input type="date" name="dob" id="dob" required><br>
	<label>Telephone: </label><input type="tel" name="tel" id="tel" required><br>
	<label>E-mail: </label><input type="email" name="email" id="email" required autocomplete="off"><br>
	<label>Password: </label><input type="password" name="pass" id="pass" required autocomplete="off"><br>
	<label></label><input type="submit" name="register" id="register" value="Register">
	</form>
	</div>
	<div class="footer">
    <p>This is the footer for the page</p>
    </div>
  </div>
</body>
</html>

Open in new window


And the register script:
<?php
//config settings
$host = 'mysite.co.uk.mysql';
$user = 'myuser';
$password = 'mypass';
$database = 'mydb';
$errorstring = "";

$dbconn = mysql_connect($host,$user,$password) or die('Could not connect to server as configuration details are incorrect');

//sanitize data
$title = trim($_POST['title']);
$firstname = trim($_POST['firstname']);
$lastname = trim($_POST['lastname']);
$dob = trim($_POST['dob']);
$tel = trim($_POST['tel']);
$email = trim($_POST['email']);

if (empty($_POST['title']) {
$errorstring = "You must enter a title"
die($errorstring};
if (empty($_POST['firstname']) {$errorstring = "You must enter a firstname"
die($errorstring};
if (empty($_POST['lastname']) {$errorstring = "You must enter a lastname"
die($errorstring};
if (empty($_POST['dob']) {$errorstring = "You must enter a date of birth"
die($errorstring};
if (empty($_POST['tel']) {$errorstring = "You must enter a telephone number"
die($errorstring};
if (empty($_POST['email']) {$errorstring = "You must enter an email address"
die($errorstring};


//protect against sql injection
$title = mysql_real_escape_string($_POST['title']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$dob = mysql_real_escape_string($_POST['dob']);
$tel = mysql_real_escape_string($_POST['tel']);
$email = mysql_real_escape_string($_POST['email']);
$pass = mysql_real_escape_string($_POST['pass']);
$pass = md5($password);


//register script
if(isset($_POST['register'])) 
{
$insertquery = "insert into tbluser(title,firstname,lastname,dob,tel,email,password)values('$title','$firstname','$lastname','$dob','$tel','$email','$pass')";
$runquery = mysql_query($query);
header('location:register_success.php');
}

?>

Open in new window


The structure is as follows:

ROOT>html>register.php
ROOT>process>register.php

the process folder is where the action script lives.

The website is located at http://www.gunnersclub.co.uk/html/register.php

Any help is greatly appreciated!
LVL 3
alexcarter404Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dimmergeekCommented:
Try this for your process>register.php code

<?php
//config settings
$host = 'mysite.co.uk.mysql';
$user = 'myuser';
$password = 'mypassword';
$database = 'mydb';
$errorstring = "";

$dbconn = mysql_connect($host,$user,$password) or die('Could not connect to server as configuration details are incorrect');

//sanitize data
$title = trim($_POST["title"]);
$firstname = trim($_POST["firstname"]);
$lastname = trim($_POST["lastname"]);
$dob = trim($_POST["dob"]);
$tel = trim($_POST["tel"]);
$email = trim($_POST["email"]);

if (empty($title))
{
    $errorstring = "You must enter a title";
    die($errorstring);    
}
if (empty($firstname)) {
    $errorstring = "You must enter a firstname";
    die($errorstring);        
}
if (empty($lastname)) {
    $errorstring = "You must enter a lastname";
    die($errorstring);        
}
if (empty($dob)) {
    $errorstring = "You must enter a date of birth";
    die($errorstring);   
}
if (empty($tel)) {
    $errorstring = "You must enter a telephone number";
    die($errorstring);   
}
if (empty($email)) {
    $errorstring = "You must enter an email address";
    die($errorstring);    
}


//protect against sql injection
$title = mysql_real_escape_string($_POST['title']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$dob = mysql_real_escape_string($_POST['dob']);
$tel = mysql_real_escape_string($_POST['tel']);
$email = mysql_real_escape_string($_POST['email']);
$pass = mysql_real_escape_string($_POST['pass']);
$pass = md5($password);


//register script
if(isset($_POST['register'])) 
{
$insertquery = "insert into tbluser(title,firstname,lastname,dob,tel,email,password)values('$title','$firstname','$lastname','$dob','$tel','$email','$pass')";
$runquery = mysql_query($query);
header('location:register_success.php');
}

?>

Open in new window


Also, mysql is going away.  You should really look into using mysqli.

mysql going away
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
Here's an explanation of what's happening with MySQL.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

What is the value of $runquery on line 49 of the register script?

Who is your hosting company?
0
GaryCommented:
If you enabled all errors this might give a real error message.

error_reporting( E_ALL ); // beginning of the code.
0
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Ray PaseurCommented:
Wow, I just looked around the site a bit.  Suggest you move all of the scripts under the WWW root directory.  You shouldn't be getting a 500 server error at all, but the directory organization and link structure seems like it could be simplified to your advantage.
0
dimmergeekCommented:
I would also do your PHP data insert on the same page.  Why a separate page to perform the function?
0
Slick812Commented:
greetings  alexcarter404, , , I went to your page at - http://www.gunnersclub.co.uk/html/register.php
and did the Resister thing and hit the "register" betton, and got the "server error" page as what you say code 500, I have seen this before so I tried this addy -
http://www.gunnersclub.co.uk/process/
and got this -
Forbidden - You don't have permission to access /process/ on this server.
you need to change the PERMISSIONS for this folder, to something that will allow WEB ACCESS


I will add, that this looks like it is a TEST for you setting up this web site, I will have to say that your registration FORM on   http://www.gunnersclub.co.uk/html/register.php   Is Very POOR, the popup calender is USELESS, get rid of it, the javascript thing for the DATE entry was a hassle, especially the year, you should change this or get rid of it, to something more user friendly
also it is Standard procedure in registration Forms to Have TWO entries for the password
you can avoid MUCH trouble, if you have a password check with a second entry.
0
alexcarter404Author Commented:
OK,
Thanks for all the replies guys I have managed to move a little further.

I have used dimmergeek's solution but I can't quite see what you changed?

It now works and sends to the registration success page but no records are added to the database. I have also amended line 49 to just use one variable, please see this code:

<?php
error_reporting( E_ALL );
//config settings
$host = 'mysite.co.uk.mysql';
$user = 'myuser';
$password = 'thisismypassword';
$database = 'mydb';
$errorstring = "";

$dbconn = mysql_connect($host,$user,$password) or die('Could not connect to server as configuration details are incorrect');

//sanitize data
$title = trim($_POST["title"]);
$firstname = trim($_POST["firstname"]);
$lastname = trim($_POST["lastname"]);
$dob = trim($_POST["dob"]);
$tel = trim($_POST["tel"]);
$email = trim($_POST["email"]);

if (empty($title))
{
    $errorstring = "You must enter a title";
    die($errorstring);    
}
if (empty($firstname)) {
    $errorstring = "You must enter a firstname";
    die($errorstring);        
}
if (empty($lastname)) {
    $errorstring = "You must enter a lastname";
    die($errorstring);        
}
if (empty($dob)) {
    $errorstring = "You must enter a date of birth";
    die($errorstring);   
}
if (empty($tel)) {
    $errorstring = "You must enter a telephone number";
    die($errorstring);   
}
if (empty($email)) {
    $errorstring = "You must enter an email address";
    die($errorstring);    
}


//protect against sql injection
$title = mysql_real_escape_string($_POST['title']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$dob = mysql_real_escape_string($_POST['dob']);
$tel = mysql_real_escape_string($_POST['tel']);
$email = mysql_real_escape_string($_POST['email']);
$pass = mysql_real_escape_string($_POST['pass']);
$pass = md5($password);


//register script
if(isset($_POST['register'])) 
{
$runquery = mysql_query(insert into tbluser(title,firstname,lastname,dob,tel,email,password)values('$title','$firstname','$lastname','$dob','$tel','$email','$pass'));
header('location:./register_success.php');
}

?>

Open in new window


The problem I have now is that no records are added to the table for some reason. I click register and get a success page but in phpmyadmin on that table it returns zero rows back to me when i select all from the table.

My host is one.com

GaryC123: I have enabled error reporting but i receive no error regarding the insert statement on my table.

Slick812: The permissions are fine I have left the processing for the registration and I no longer get a 500 error. Also all the validation is done in HTML 5 this is where the datepicker field is coming from not javascript.

Dimmergeek: I thought it was good practice to pass html fields to a seperate php processing page is this not the case?

I do have an index on the table which is an auto increment but this shouldn't affect records being added should it?

Any more ideas guys???
0
Slick812Commented:
OK, you need to do this registration processing page FIRST as a development page, and do NOT transfer to another page with -
header('location:./register_success.php');

, the way you have it now, you can NEVER see any PHP error or warning messages, and be able to work on this page until it gets you the results you need
in this line -
$runquery = mysql_query(insert into tbluser(title,firstname,lastname,dob, tel,email,password) values('$title','$firstname','$lastname','$dob','$tel','$email','$pass'));

the SQL statement needs to be a string, also on any registration page you will absolutety need error checking, for instance -

$runquery = mysql_query("insert into tbluser(title,firstname,lastname,dob, tel,email,password) values('$title','$firstname','$lastname','$dob','$tel','$email','$pass')");
if (!$runquery) die("ERROR, mysql_query FAILED!");


also you need to place this line -
if(isset($_POST['register']))
before ALL of the other lines of code for $_POST access like -
$title = trim($_POST["title"]);
and move this DB connection AFTER ALL of the verifications

if (empty($email)) {
    $errorstring = "You must enter an email address";
    die($errorstring);    
}
$dbconn = mysql_connect($host,$user,$password) or die('Could not connect to server as configuration details are incorrect');

I did NOT write a code block for you that shows some corrections, I thought it better that you work through your code, line by line and try to see what it does, and try to understand WHY and WHEN the code lines are doing the right thing at the right time, you seem to do a copy paste, without the fundamentals of what that code is doing. This code is not very good for a registration processing page.
0
Ray PaseurCommented:
There are a couple of things you might want to add to the script.  First of all, MySQL (in any of its versions and extensions) is not a black box.  It returns all sorts of values to your PHP script, and the PHP programmer must write tests for these return values.  Example:

$dbconn = mysql_connect($host,$user,$password) or die('Could not connect to server as configuration details are incorrect');

How would you know whether the mysql_connect() function worked?  You would go to the php.net web site and read the description of the function.  It would tell you what the possible return values might be.  Usually php.net will tell you how to test the return values and detect errors, including how to visualize the errors.

Another example:

$runquery = mysql_query(insert into tbluser(title,firstname,lastname,dob,tel,email,password)values('$title','$firstname','$lastname','$dob','$tel','$email','$pass'));

This statement failed, but because your script is not looking for errors, you get a blank response instead of an error message than can help you fix the problem.  Here are my two top suggestions for this script.

1. Add error_reporting(E_ALL); to the top of the script
2. Follow the guidance in this article that shows how to test for success or failure of a query and how to visualize the errors, if any.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

And overall, here is my suggestion for you to get started in PHP and MySQL.  It won't happen overnight, but if you give yourself the advantage of some structured learning, you will be way ahead of those poor folks who try to learn PHP by copying examples found at random on the internet, or by trial and error.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
0
alexcarter404Author Commented:
Thanks for all the advice guys! Basically I am developing my first PHP site for a uni module which I wish I never took now! I am going to get reading on the PHP site tonight to get error checking and everything sorted! My next problem is making the site compatible with all browsers as it currently only works in IE7 but I will look at that another day!

Slick thank you for your help with my code I have made some amendments as you said and can see that it is the insert query that is failing. When adding data to a table with an auto increment for the ID do you have to specify it in the INSERT query or should it just automatically add its data in?

This is the new code below:
<?php
if(isset($_POST['register'])) 
{
error_reporting( E_ALL );

//sanitize data
$title = trim($_POST["title"]);
$firstname = trim($_POST["firstname"]);
$lastname = trim($_POST["lastname"]);
$dob = trim($_POST["dob"]);
$tel = trim($_POST["tel"]);
$email = trim($_POST["email"]);

if (empty($title))
{
    $errorstring = "You must enter a title";
    die($errorstring);    
}
if (empty($firstname)) {
    $errorstring = "You must enter a firstname";
    die($errorstring);        
}
if (empty($lastname)) {
    $errorstring = "You must enter a lastname";
    die($errorstring);        
}
if (empty($dob)) {
    $errorstring = "You must enter a date of birth";
    die($errorstring);   
}
if (empty($tel)) {
    $errorstring = "You must enter a telephone number";
    die($errorstring);   
}
if (empty($email)) {
    $errorstring = "You must enter an email address";
    die($errorstring);    
}

//protect against sql injection
$title = mysql_real_escape_string($_POST['title']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$dob = mysql_real_escape_string($_POST['dob']);
$tel = mysql_real_escape_string($_POST['tel']);
$email = mysql_real_escape_string($_POST['email']);
$pass = mysql_real_escape_string($_POST['pass']);
$pass = md5($password);

//config settings
$host = 'gunnersclub.co.uk.mysql';
$user = 'gunnersclub_co_';
$password = 'A0308c1991';
$database = 'gunnersclub_co_';
$errorstring = "";

$dbconn = mysql_connect($host,$user,$password) or die('Could not connect to server as configuration details are incorrect');

//register script

$runquery = mysql_query("insert into tbluser(title,firstname,lastname,dob, tel,email,password) values('$title','$firstname','$lastname','$dob','$tel','$email','$pass')");
if (!$runquery) die("ERROR, mysql_query FAILED!");
//header('location:./register_success.php');
}

?>

Open in new window


I will definitely need to get onto the error checking tonight!
0
alexcarter404Author Commented:
I am pretty sure that the $runquery variable is not being set for some reason....
0
Ray PaseurCommented:
You never have to put information about the AUTO_INCREMENT key into an INSERT; the SQL engine will do that for you.

You want to get OFF the MySQL extension.  PHP is removing support for MySQL.  That's one of the reasons I suggested that you should read this article, and I am suggesting it again.  It will show you exactly what you must do to keep your scripts running in the future.  You will probably find, as I did, that the easiest 1:1 conversion from MySQL was to MySQLi using the object-oriented notation.  The article will also show you how to test for errors and visualize any error messages.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

In the script above, it looks like there was no selection of the data base.  The script connected to the server at line 57, but did not select a data base, nor did it name a data base in the query.  When you make the conversion to MySQLi you will see that the connect and select are done with a single statement.
0
alexcarter404Author Commented:
Ahh I see now I haven't set a database I have also narrowed the issue down to the mysql real escape for some reason this is returning a null to my variable I will get back later when I am back on it!
0
Ray PaseurCommented:
MySQL_Real_Escape_String() depends on a data base connection.  

Fortunately all of the PHP functions are documented in the online man pages, which are required reading if you're not 100% certain you know everything about the function your code is using.  In the instant case, the link_identifier is the thing you want to know about.

Most designs will put the data base connection and selection at the top of the script, right after error_reporting(E_ALL);
0
alexcarter404Author Commented:
Hi All,
Thank you for all the help!
I took your advice and decided to switch to mysqli and also added some error checking to each step of the insert process. Below is the final code for the page, however this will probably be edited later in the project to be converted to an object oriented approach. Are there any other suggestions I should add in whilst I am here looking at it??

<?php
error_reporting( E_ALL );
if(isset($_POST['register'])) 
{
//config settings
$host = mysite.co.uk.mysql';
$user = 'myuser';
$password = 'mypassword';
$database = 'mydb';
$errorstring = "";


//sanitize data
$title = trim($_POST["title"]);
$firstname = trim($_POST["firstname"]);
$lastname = trim($_POST["lastname"]);
$dob = trim($_POST["dob"]);
$tel = trim($_POST["tel"]);
$email = trim($_POST["email"]);

if (empty($title))
{
    $errorstring = "You must enter a title";
    die($errorstring);    
}
if (empty($firstname)) {
    $errorstring = "You must enter a firstname";
    die($errorstring);        
}
if (empty($lastname)) {
    $errorstring = "You must enter a lastname";
    die($errorstring);        
}
if (empty($dob)) {
    $errorstring = "You must enter a date of birth";
    die($errorstring);   
}
if (empty($tel)) {
    $errorstring = "You must enter a telephone number";
    die($errorstring);   
}
if (empty($email)) {
    $errorstring = "You must enter an email address";
    die($errorstring);    
}

//create database connection
$con=mysqli_connect($host,$user,$password,$database);

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

//protect against SQL injection
$title = mysqli_real_escape_string($con, $title);
$firstname = mysqli_real_escape_string($con, $firstname);
$lastname = mysqli_real_escape_string($con, $lastname);
$dob = mysqli_real_escape_string($con, $dob);
$tel = mysqli_real_escape_string($con, $tel);
$email = mysqli_real_escape_string($con, $email);
$pass = mysqli_real_escape_string($_POST['pass']);
$pass = md5($pass);

//register script
$sql="INSERT INTO tbluser (title, firstname, lastname,dob,tel,email,password)
VALUES
('$title','$firstname','$lastname','$dob','$tel','$email','$pass')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added";

mysqli_close($con);

header('location:./register_success.php');
}
?>

Open in new window


Once again thank you for all the help and pointers and I will be using the man pages and other documentation suggested in future!
0
Ray PaseurCommented:
This is probably how I would lay it out, just for starters.  I included some links to the relevant man pages.  I think you will find the OOP version of MySQLi much easier to use in the long run, and now is a good time to begin using it.

There is one caveat here, and that is a dependency on the mapping of the form input control names to the data base column names.  I might also want to add a "salt" to the password string.  The md5() function produces highly recognizable values for unsalted passwords.

<?php // RAY_temp_alexcarter404.php
error_reporting(E_ALL);

// THE ABSOLUTE MINIMUM YOU MUST UNDERSTAND TO USE PHP AND MYSQLI
// MAN PAGE: http://php.net/manual/en/mysqli.overview.php
// MAN PAGE: http://php.net/manual/en/class.mysqli.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-stmt.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-result.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-warning.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-sql-exception.php <-- DID NOT WORK PHP 5.3+, MySQL 5.1+
// MAN PAGE: http://php.net/manual/en/mysqli.construct.php
// MAN PAGE: http://php.net/manual/en/mysqli.real-escape-string.php
// MAN PAGE: http://php.net/manual/en/mysqli.query.php
// MAN PAGE: http://php.net/manual/en/mysqli.errno.php
// MAN PAGE: http://php.net/manual/en/mysqli.error.php
// MAN PAGE: http://php.net/manual/en/mysqli.insert-id.php
// MAN PAGE: http://php.net/manual/en/mysqli-result.num-rows.php
// MAN PAGE: http://php.net/manual/en/mysqli-result.fetch-array.php
// MAN PAGE: http://php.net/manual/en/mysqli-result.fetch-object.php

// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";

// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);

// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
    $err
    = "CONNECT FAIL: "
    . $mysqli->connect_errno
    . ' '
    . $mysqli->connect_error
    ;
    trigger_error($err, E_USER_ERROR);
}

// THE FIELDS WE ARE EXPECTING FROM THE FORM
$fields = array
( 'title'
, 'firstname'
, 'lastname'
, 'dob'
, 'tel'
, 'email'
, 'pass'
)
;

// THE SANITIZED DATA AND THE ERROR TANK
$qdata = array();
$error = array();

// CHECKING AND SANITIZING THE EXTERNAL DATA
if (empty($_POST)) die();

// ITERATE OVER OUR INTERNAL ARRAY OF EXPECTED INFORMATION
foreach ($fields as $field)
{
    // ERROR SIGNAL FOR MISSING DATA
    if (empty($_POST[$field]))
    {
        $error[] = "You must enter a value for $field";
    }
    $qdata[$field] = $mysqli->real_escape_string($_POST[$field]);
}

// SPECIAL PROCESSING FOR PASSWORD
$qdata['pass'] = md5($_POST['pass']);

// IF ANY ERRORS
if (!empty($error))
{
    foreach ($error as $ermsg)
    {
        echo PHP_EOL . $ermsg;
    }
    // MAYBE MAKE THIS A LITTLE MORE USER FRIENDLY
    die('Please Try Again');
}

// EVERYTHING IS SANITARY - CREATE THE QUERY STRING
$keys = array_keys($qdata);
$keys = implode(',', $keys);
$vals = "'" . implode("','", $qdata) . "'";
$sql  = "INSERT INTO tbluser ( $keys ) VALUES ( $vals )";
$res  = $mysqli->query($sql);

// IF mysqli::query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = 'QUERY FAILURE:'
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    . ' QUERY: '
    . $sql
    ;
    trigger_error($err, E_USER_ERROR);
}

// REDIRECT TO THE "THANK YOU" PAGE
header('location:./register_success.php');
exit;

Open in new window

Please let me know if you have any questions, ~Ray
0
Slick812Commented:
looked at your code in comment ID: 39537568 , ,  you need to be more careful and not put passwords and database access addy in your posts.

and you now use the newer Improved MySQL-
$con=mysqli_connect(
which is a real step forward!

and you do a really MINIMAL user input checking with -
if (empty($title))

This is NOT going to work out for you!, I can tell you this from direct experience, not from reading some How-To web site or the PHP user manual
FIRST and FOREMOST! ! you really have to start with the attitude of "I have to make my web site User-friendly, and EASY-TO Understand and operate ! !. You absolutely have to do development with this goal, please look at how you display your ERROR output -
 die($errorstring);
This is TERRIBLE user experience to help them to use your site for text data to database user input (text typing) and have the more than occasional Mis-Typed text input. I realize that this is a page that you are just testing how to do a mysql database insert, but the age old die( ) is not really useful any more (my opinion), the exit( ) is a little more up to date, HOWEVER, these methods for php page sudden death should only be used if there is a compelling need to to end all functioning, which is certainly NOT the case with   if (empty($title))  
after checking the user inputs for String Length and valid characters just before the mysql database Connection have a test for the error string, and if empty (false) then do the DB connection and insert, if errors, then display the error string an a red DIV to get the attention of the user.
if (!$errorstring) {
    $con=mysqli_connect($host,$user,$password,$database);
    // other code
    if (!mysqli_query($con,$sql))
    } else
    {
// place this div BELOW the <body> tag
    echo '<div style="color:white; background: red;>'.$errorstring.'</div>';
    }

ALSO for development NEVER place a page re-location -
header('location:./register_success.php');
if you do you may never see any Error warning php messages, get it tested and then add in the re-location.

you may consider that your database only has certain length varchar, so you need to test input for length
if ((strlen($title) < 4) || (strlen($title) > 24)) {
   $errorstring .= "ERROR, Title MUST be more than 3 charaters and LESS than 25 charaters<br />";
   }

the password protection by the MD5 hash is no longer valid, it has not been valid for more than 10 years, PHP have a much better password hash function called - hash_hmac( ) - which is specifically made for EXTRA seeded scrambling of the hash output, and is 10 times better than just adding a seed string to a normal hash.
$hashed =hash_hmac('sha256',$password,$seed);
0
alexcarter404Author Commented:
Hi Slick,
Cheers for the feedback. To get this to display in a red div would i need to run the process from the actual register page rather than using a separate script?

Ray - the OOP code you provided is great! I won't implement this just yet as I will be learning OOP PHP in the next few weeks at university so would prefer to understand it first, I can read quite a lot of it but would prefer to fluently understand the content of it. The man pages you provided will be extremely helpful, I will give these a read tomorrow when i get a chance.

Thanks for all the help so far everyone, Starting to think I may actually pass this module!
0
Slick812Commented:
you say - "run the process from the actual register page rather than using a separate script?", , I can not tell from what you have posted, but running a separate "Module" as you say, could be inefficient for your code efforts, if there are user input errors you need to display them AND have the Form there to correct their entries, preferably filled OUT with the OLD correct  input (so they do not have to re-type), I almost always have ALL PHP functioning for input testing and database insert ON the PHP registration page, if I need other CMS or MVC modules, or database or verification Class php files , then these are added as PHP include to the registration page.
I would recommend that you delay jumping in to trying OOP PHP, until you are very familiar wid PHP, I have tried to show-teach Object programming to some, and they did not have the general programming and PHP skills to make any sense of the OOP. PHP is NOT an object oriented language, and can do very great web sites without a single line of OOP code, althouh OOP does have some advantages ONLY if you know how to use them.
0
Ray PaseurCommented:
PHP is NOT an object oriented language,
I'll give you that at PHP3 and PHP4, but about 8 years ago at PHP5, the OOP model matured.  A lot.

That said, OOP design and OOP notation are not at all the same thing.  The MySQLi extension in OOP notation gives a much easier path to MySQL code conversion because the function calls have the arguments in the same order as the older and obsolete MySQL extension.  If you convert procedural MySQL to procedural MySQLi you will have to change the function call arguments in every single query.  If you listen to the little voices in your head you will surely see that the PHP Gods are saying, "STOP writing procedural code!"  And that is very good advice!
0
alexcarter404Author Commented:
I will have a look at OO when I get a chance. I think my main priority is learning PHP properly first! One final thing. On this registration form I have now switched to using a SHA-512 hash function for the time being to make it slightly more secure (I will be using salts etc at a later date). For some reason for different strings I always get the same hash which means this is what is stored in the database. The hash is:

cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e

And the code is:
<?php
error_reporting( E_ALL );
if(isset($_POST['register'])) 
{
//config settings
$host = '';
$user = '';
$password = '';
$database = '';
$errorstring = "";

//sanitize data
$title = trim($_POST["title"]);
$firstname = trim($_POST["firstname"]);
$lastname = trim($_POST["lastname"]);
$dob = trim($_POST["dob"]);
$tel = trim($_POST["tel"]);
$email = trim($_POST["email"]);

if (empty($title))
{
    $errorstring = "You must enter a title";
    die($errorstring);    
}
if (empty($firstname)) {
    $errorstring = "You must enter a firstname";
    die($errorstring);        
}
if (empty($lastname)) {
    $errorstring = "You must enter a lastname";
    die($errorstring);        
}
if (empty($dob)) {
    $errorstring = "You must enter a date of birth";
    die($errorstring);   
}
if (empty($tel)) {
    $errorstring = "You must enter a telephone number";
    die($errorstring);   
}
if (empty($email)) {
    $errorstring = "You must enter an email address";
    die($errorstring);    
}

//create database connection
$con=mysqli_connect($host,$user,$password,$database);

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

//protect against SQL injection
$title = mysqli_real_escape_string($con, $title);
$firstname = mysqli_real_escape_string($con, $firstname);
$lastname = mysqli_real_escape_string($con, $lastname);
$dob = mysqli_real_escape_string($con, $dob);
$tel = mysqli_real_escape_string($con, $tel);
$email = mysqli_real_escape_string($con, $email);
$pass = mysqli_real_escape_string($_POST['pass']);
$pass = hash('sha512',$pass);

//register script
$sql="INSERT INTO tbluser (userid,title,firstname,lastname,dob,tel,email,password)
VALUES
('','$title','$firstname','$lastname','$dob','$tel','$email','$pass')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }

mysqli_close($con);

header('location:./register_success.php');
}
?>

Open in new window


Any ideas? The hash works fine on my login form and generates a different hash correctly!
0
Slick812Commented:
This is my last comment on this one, because you are using such a BAD php code for this type of "Registration", I mean really NON FUNCTIONAL php code,
for instance you have this -
//sanitize data
$title = trim($_POST["title"]);

This absolutely does NOT do any "sanitize data" at all = NONE

this is all I will say about your Hashing treatment, and that you absolutly do not understand the steps you are taking for hashing
you have -
$pass = mysqli_real_escape_string($_POST['pass']);
$pass = hash('sha512',$pass);

first you do not need to do a real escape function if you are going to HASH a string, please try and do some reading to find out WHY the mysqli_real_escape_string( ) is necessary for some strings and useless (like for hashes here) for others,

any sha256 HASHING output will always be different if the input is different, so if the output is always the same, then the input is always the same, also the sha256 HASHING output will be a  generated even if your input is an empty string as in -
$pass = hash('sha512', "");

and I think this is what is happening for you, please check that you are using the correct spelling for your POST access as you have
$_POST['pass']

but it may be -
$_POST['password']

good luck
0
Slick812Commented:
@Ray_Paseur, I do not agree with your PHP gods statement at all NONE, but I guess that my programming Gods are not your programming Gods

you might consider not trying to push PHP tech on people that do not understand that tech
0
alexcarter404Author Commented:
Thanks for the help all, It's now up and running sort of and I used the procedural approach for now. I will look into an OO approach at a later date. This is only a test site so will not actually be used, it's all about showing PHP, HTML5, CSS3, javascript and google API use. Thanks for the help anyway I will allocate points now.
0
alexcarter404Author Commented:
Thanks everyone great help!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.