Solved

Advanced PHP form submission to Database issue help

Posted on 2017-06-16
11
30 Views
Last Modified: 2017-06-21
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
Comment
Question by:Mike Moore
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 78

Assisted Solution

by:arnold
arnold earned 167 total points
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
 

Assisted Solution

by:Mike Moore
Mike Moore earned 0 total points
thanks for your comment,

Just tried but still no luck.

not even getting the error message back??
0
 
LVL 78

Assisted Solution

by:arnold
arnold earned 167 total points
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
Transaction Monitoring Vs. Real User Monitoring

Synthetic Transaction Monitoring Vs. Real User Monitoring: When To Use Each Approach? In this article, we will discuss two major monitoring approaches: Synthetic Transaction and Real User Monitoring.

 

Assisted Solution

by:Mike Moore
Mike Moore earned 0 total points
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
 
LVL 78

Assisted Solution

by:arnold
arnold earned 167 total points
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
 
LVL 7

Assisted Solution

by:Swatantra Bhargava
Swatantra Bhargava earned 167 total points
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
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 166 total points
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
 

Assisted Solution

by:Mike Moore
Mike Moore earned 0 total points
thanks for all your comments, I don't think the error is in the INSERT as I have tried everything.
0
 

Accepted Solution

by:
Mike Moore earned 0 total points
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
 
LVL 110

Expert Comment

by:Ray Paseur
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
 

Author Closing Comment

by:Mike Moore
I figured it out myself
0

Featured Post

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Join & Write a Comment

When it comes to protecting Oracle Database servers and systems, there are a ton of myths out there. Here are the most common.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question