Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Advanced PHP form submission to Database issue help

Posted on 2017-06-16
11
Medium Priority
?
55 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 80

Assisted Solution

by:arnold
arnold earned 668 total points
ID: 42180866
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
ID: 42180869
thanks for your comment,

Just tried but still no luck.

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

Assisted Solution

by:arnold
arnold earned 668 total points
ID: 42180877
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
Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

 

Assisted Solution

by:Mike Moore
Mike Moore earned 0 total points
ID: 42180881
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 80

Assisted Solution

by:arnold
arnold earned 668 total points
ID: 42180889
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 668 total points
ID: 42180904
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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 664 total points
ID: 42180966
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
ID: 42181151
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
ID: 42181162
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 111

Expert Comment

by:Ray Paseur
ID: 42181457
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
ID: 42186807
I figured it out myself
0

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows how to get a list of available printers for display in a drop-down list, and then to use the selected printer to print an Access report or a Word document filled with Access data, using different syntax as needed for working with …
In this blog, we’ll look at how improvements to Percona XtraDB Cluster improved IST performance.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses

650 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