• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 79
  • Last Modified:

Advanced PHP form submission to Database issue help

Hi experts.

I am coding a login system, However when I submit a registration form it just won't save the data into the database. im sure all my code is valid and can't seem to find the reason why??

no error messages are displayed and I have tested connection to the database and it connects fine.

I have set some code to echo "USER REGISTERED" if the data was submitted and stored in the database successfully but I can't get that message to show so there must be something im missing.

Please see code below, If you have any suggestions or spot any errors please let me know. Thanks.

login.php

<?php

// includes original html for login page
include('includes/header.php');
include('includes/login_form.php');
include('includes/footer.php');

/*
$sql = "select * from users"; // Pull user info from Database.
$result = query($sql);
confirm($result);
$row = fetch_array($result);

echo $row['username']; // Get username from database.
*/

?>

Open in new window


register.php

<?php

// includes original html for Create Account page
include('includes/header.php');
include('includes/create_account_form.php');
include('includes/footer.php');

?>

Open in new window


header.php

<?php include("functions/init.php"); // includes all code for login  
?>

<!DOCTYPE html>
<!------------------------------------------------------------------------------------------
WARNING!
Copyright (C) Mike Z Moore - All Rights Reserved
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
Design & Code by Mike Z Moore, mikezmoore@icloud.com, May 2017, www.mikezmoore.com
------------------------------------------------------------------------------------------->
<html>

<head>
    <title>Turbo | Login</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/login.css">
    <link href="https://fonts.googleapis.com/css?family=Maven+Pro|Open+Sans" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="css/responsive.css">
    <script src="js/script.js"></script>
</head>

Open in new window


init.php

<?php ob_start(); //  built in function to turn on output buffering, i will use this for redirection.

session_start(); // Built in function to start the login session.

//includes Database configurtion.
include("functions/db.php");

//includes php functions.
include("functions/functions.php");

/* Checks if database is connected.
if($con){
    
// Message to display if connection is true   
echo 'We have lift off!';
    
}
*/

?>

Open in new window


functions.php

<?php 

/************** Helper functions **************/

function clean($string){  
return htmlentities($string); 
}

function redirect($location){  
return header('location: {$location}');       
}

function set_message($message){ // Function to make values global for session messages.   
if(!empty($message)){    
$_SESSION['message'] = $message;    
}else{   
    $message = '';   
 }   
} 

function display_message(){ // Displays the session message with the value we set to it.   
if(isset($_SESSION['message'])){
echo $_SESSION['message'];
unset($_SESSION['message']);
 }  
}     

function token_generator(){ // Function for extra form security.
$token = $_SESSION['token'] = md5(uniqid(mt_rand(), true)); // Creates a unique id with a random number as a prefix - More secure than static prefix.   
return $token;
}

/************** Helper functions **************/

/************** Validation functions **************/

function validation_errors($error_message){ //Function for displaying validation errors

// HTML & CSS Alert Box
    
$error_message = <<< EOS

<style>
html,
body {
	height: 100%;
}

.container {
	display: flex;
	height: 10%;
	justify-content: center;
	align-items: center;
}

.rectangle {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	positon: relative;
	width: 50px;
	height: 50px;
	background: #e74c3c;
	transform: scale(0);
	border-radius: 50%;
	color: white;
    margin-bottom: 10px; 
	opacity: 0;
	overflow: hidden;
	animation: scale-in .3s ease-out forwards,
		expand .35s .25s ease-out forwards;
}

.notification-text {
	display: flex;
	align-items: center;
	padding: 0 16px;
	font-family: 'Roboto', sans-serif;
	font-size: 14px;
	animation: fade-in .65s ease-in forwards;
}

@keyframes scale-in {
	100% {
		transform: scale(1);
		opacity: 1;
	}
}

@keyframes expand {
	50% {
		width: 350px;
		border-radius: 6px;
	}
	100% {
		width: 414px;
        height: 40px;
		border-radius: 4px;
		box-shadow: 0px 1px 3px 0px rgba(0,0,0,.2),
								0px 1px 1px 0px rgba(0,0,0,.14),
								0px 3px 3px -1px rgba(0,0,0,.12);
	}
}

@keyframes fade-in {
	0% {
		opacity: 0;
	}
	100% {
		opacity: .8;
	}
}

.notification-close {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  font-size: 18px;
  border-radius: 50px;
  width: 18px;
  height: 18px;
  line-height: 15px;
  text-align: center;
  text-decoration: none;
  color: white;
}
</style>

<div id="hide">
<div class='container'>
 <div class='rectangle'>
  <div class='notification-text'>
   <span>&nbsp;&nbsp;$error_message</span>
   <span class="notification-close">&times;</span>
   </div>
  </div>
 </div>
</div> 

EOS;
return $error_message; 
}

function email_exists($email){ // This function checks to see if the email already exists in the database.
$sql = "SELECT id FROM users WHERE email = '$email'";
$result = query($sql);
if(row_count($result) == 1){
return true;
}else{
return false;    
 }    
}

function username_exists($username){ // This function checks to see if the username already exists in the database.
$sql = "SELECT id FROM users WHERE username = '$username'";
$result = query($sql);
if(row_count($result) == 1){
return true;
}else{
return false;    
 }    
}

function validate_user_registration(){

$errors = [];
$min = 3;
$max = 50;
    
if($_SERVER['REQUEST_METHOD'] == 'POST'){

$first_name           = clean($_POST['fname']);
$last_name            = clean($_POST['lname']);
$username             = clean($_POST['username']);
$email                = clean($_POST['email']);
$password             = clean($_POST['password']);
$confirm_password     = clean($_POST['confirmpassword']); 

    
// Check First Name validation for min & max characters    
    
if(strlen($first_name) < $min){
$errors[] = "Your first name cannot be less than {$min} characters";    
} 
if(strlen($first_name) > $max){
$errors[] = "Your first name cannot contain more than {$max} characters";    
}

// Check Last Name validation for min & max characters 
    
if(strlen($last_name) < $min){
$errors[] = "Your last name cannot be less than {$min} characters";    
} 
if(strlen($last_name) > $max){
$errors[] = "Your last name cannot contain more than {$max} characters";    
} 
    
// Check if username already exists in database 
    
if(username_exists($username)){
$errors[] = "Sorry, That username is alreaady taken"; 
}    
    
// Check username validation for min & max characters
    
if(strlen($username) < $min){
$errors[] = "Your username cannot be less than {$min} characters";    
} 
if(strlen($username) > $max){
$errors[] = "Your username cannot contain more than {$max} characters";    
 } 
      
// Check if email already exists in database 
    
if(email_exists($email)){
$errors[] = "Sorry, That email is already in use"; 
}
    
// Check email validation for max characters
    
if(strlen($email) > $max){
$errors[] = "Your email cannot contain more than {$max} characters";    
 } 
    
// Check if passwords match
    
if($password !== $confirm_password){
$errors[] = "Your passwords do not match!";     
 }    
}
    
if(!empty('$errors')){ // If theres an error it will call this function 
foreach($errors as $error){  

    //Display Error messages
    echo validation_errors($error); 
  }  
 }else{ // if there is no error it will call this function
if(register_user($first_name, $last_name, $username, $email, $password)){
echo "USER REGISTERED";
  }
 }
    
}
/************** Validation functions **************/

function register_user($first_name, $last_name, $username, $email, $password){ 

$first_name = escape($first_name);
$last_name = escape($last_name);  
$username = escape($username);  
$email = escape($email); 
$password = escape($password);   

if(email_exists($email)){
return false;   
}elseif(username_exists($username)){
return false;   
}else{
$password = md5($password);
$validation_code = md5($username + microtime());
$sql = "INSERT INTO users(first_name, last_name, username, email, password, validation_code, active)";
$sql.= " VALUES('$first_name', '$last_name', '$username', '$email', '$password', '$validation_code', 0)";
$result = query($sql);
confirm($result);
return true;
 }
}

?>

Open in new window


db.php

<?php
// Establish a database connection
$con = mysqli_connect('localhost', 'root', 'root', 'login_db');

/*************** Customs db helper functions ***************/


function row_count($result){  // Counts rows in table.
return mysqli_num_rows($result);    
}


function escape($string){ // Custom function to clean database.
global $con; // Get connection    
return mysqli_real_escape_string($con, $string); // Escape data 
}

function query($query){ // Custom function to query database when called.
global $con; // Get connection
return mysqli_query($con, $query); // Everytime i want to make a query i will use this function.
}

function confirm($result){ // Confirm the query is ok.
global $con; // Get connection
if(!$result){
die("QUERY FAILED" . myqli_error($con));
 }
}

function fetch_array($result){
global $con; // Get connection    
return mysqli_fetch_array($result); // Gets the result.   
}

/*************** Customs db helper functions ***************/

?>

Open in new window


Any help would be very appreciated.

Thanks.
0
Mike Moore
Asked:
Mike Moore
  • 5
  • 3
  • 2
  • +1
9 Solutions
 
arnoldCommented:
You have calls, but at no point do you check whether

You need an else on your register_user to get an error of the registration foes not go through.

You should not start/establish connection on load, but when it is needed.
Have a function check_connection. If present, it's gone, if not establish.
0
 
Mike MooreAuthor Commented:
thanks for your comment,

Just tried but still no luck.

not even getting the error message back??
0
 
arnoldCommented:
Instead of return mysqli_exec, assign the value to a variable run your tests and the. Return a response.

0 usually means good, 1 or larger means bad.

Your checks might be reversed and you do not use the error notification...

$con=mysqli_connect you do not test whether a connection is actually established.

Trying to untangle.
Does your query function with select return data?
double check the insert syntax

Do you get a response that says "User registered"?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
Mike MooreAuthor Commented:
I checked connection to database using

if($con){
   
// Message to display if connection is true  
echo 'Connected!';
}

and it returned true.

I then queried the database and was able to return a user that was manually added to the database using :

$sql = "select * from users"; // Pull user info from Database.
$result = query($sql);
confirm($result);
$row = fetch_array($result);

echo $row['username']; // Get username from database.

I also checked the INSERT syntax and seems fine

however after all tests successfully connected I still can't insert the data into the database???
0
 
arnoldCommented:
When you run the register_user function, you are not testing results.
Do you get a response, "USER REGISTERED"

Check for errors after attempting to register users.
And an else to the register_user in the functions.db

If register_user

else {
echo "registration failure: output errors"

You might have space related issue insert into users () values ();...
0
 
Swatantra BhargavaTeam LeaderCommented:
Hi

change your Insert query with below and try

$sql = "INSERT INTO users(first_name, last_name, username, email, password, validation_code, active)";
$sql.= " VALUES('".$first_name."', '".$last_name."', '".$username."', '".$email."', '".$password."', '".$validation_code."', 0)";
$result = query($sql);
0
 
Ray PaseurCommented:
You are not the first to deal with the issues associated with client registration and login.  We have an article here at E-E that shows the design and provides tested and working code examples!
https://www.experts-exchange.com/articles/2391/PHP-Client-Registration-Login-Logout-and-Easy-Access-Control.html

If you're new to PHP and want to learn the language, this article can help you find dependable learning resources.  There is a lot of junk on the internet.  Stick with these examples, and you will save yourself a lot of time on the dead-end side trails.
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
0
 
Mike MooreAuthor Commented:
thanks for all your comments, I don't think the error is in the INSERT as I have tried everything.
0
 
Mike MooreAuthor Commented:
hi guys I have figured it out after doing some intensive debugging.

the error was a very silly typo and was in this line :  if(!empty('$errors')){ // If theres an error it will call this function.

I removed the quotes from the function perimeters. $errors. it was suppose to be :

if(!empty($error')){ // If theres an error it will call this function.

Thanks for all your help.
0
 
Ray PaseurCommented:
Just a note for reference, and going forward.  Here is how quotation marks work in PHP.
https://www.experts-exchange.com/articles/12241/Quotation-Marks-in-PHP.html
0
 
Mike MooreAuthor Commented:
I figured it out myself
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now