Data is not inserting into MySQL DB [duplicate] - php

This question already has an answer here:
PHP PDO prepared statements
(1 answer)
Closed 1 year ago.
I am using PHP and PDO, the problem is when I click on the submit button the data is not inserted into the Database. There are no errors at all, I am not sure what's causing it. I've tried a lot of things and still can't manage to find a solution.
This is my code:
<?php
function cl($info){
return preg_replace("|[^\w]|", "", $info);
}
function cl2($info){
return preg_replace("|[^\w]|", "", $info);
}
function check_email($email){
$exit = FALSE;
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
return $exit = TRUE;
}
else {
return $exit;
}
}
if (isset($_POST['register'])) {
$errors = [];
$username = cl($_POST['username'] ?? '');
$password = cl2($_POST['password'] ?? '');
$email = $_POST['email'] ?? '';
try {
$conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
$check_username = $conn->prepare("SELECT * FROM accounts WHERE name = :username");
$check_username->bindParam(':username', $username, PDO::PARAM_STR);
$check_username->execute();
if($check_username->rowCount()) {
array_push($errors, 'Username already in use, please select a new one.');
} else if(empty($username) || strlen($username) < 4 || strlen($username) > 13) {
array_push($errors, 'Invalid username, please select another one.');
} else if(empty($password) || strlen($password) < 4 || strlen($password) > 20) {
array_push($errors, 'Invalid password, please select another one.');
} else if(empty($email) || !check_email($_POST['email'])) {
array_push($errors, 'Invalid password, please select another one.');
}
if(empty($errors)) {
$query = $conn->prepare("INSERT INTO accounts (name,password,email) VALUES ($username,$password,$email)");
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->execute();
echo '<br />';
echo ' <div class="alert alert-success text-center" role="alert">
Account created succesfully.
</div>';
} else {
foreach($errors as $error) {
echo '<br />';
echo '<div class="alert alert-danger text-center" role="alert">';
echo $error;
echo '</div>';
}
}
}
?>
And the form:
<form method="POST">
<div class="form-group">
<label for="InputUsername">Username</label>
<input type="text" class="form-control" id="InputUsername" placeholder="Enter username" name="username">
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="inputPassword" placeholder="Password" name="password">
</div>
<div class="form-group">
<label for="inputEmail">Email address</label>
<input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Enter email" name="email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="rules">
<label class="form-check-label" for="rules">I have read the rules before creating a new account.</label>
</div>
<br />
<button type="submit" class="btn btn-primary" name="register">Submit</button>
</form>
I am trying this using Wamp, in a local development. If anyone could help me I would really appreciate it.
Okay now after adding this to my code:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I am getting the following error:
Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.accounts' doesn't exist
But the table exists in my db. This is acting weird.

From what I can see this line is wrong
$query = $conn->prepare("INSERT INTO accounts (name,password,email) VALUES ($username,$password,$email)");
It should be
$query = $conn->prepare("INSERT INTO accounts (name,password,email) VALUES (:username,:password,:email)");
I THINK it would've worked had you put quotes around the variables but you look like you want to prevent sql injection properly.

Related

Cannot display alert once the user login inputs incorrect credentials PHP PDO

index.php
This is the login form
<div class="modal-body">
<form action="loginPDO.php" method="post">
<?php if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
} ?>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter Username" class="form-control">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="login" id="login" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-info">Register</button>
</div>
</form>
</div>
loginPDO.php
<?php
include 'dbconnection.php';
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
header("location:index.php");
}
else
{
$query = "SELECT * FROM users WHERE username = :username AND password = :password";
$statement = $conn->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:dashboard.php");
}
else
{
$message = '<label>Wrong Data</label>';
header("location:index.php");
}
}
}
?>
Hi Guys, I want to know how to display the alert message once the user inputs incorrect credentials
For example, Imagine the user inputs wrong credentials once the user clicks the login button it automatically appears the alert message above Username.
$message just exists in file loginPDO.php and ...
$message = '<label>Wrong Data</label>';
header("location:index.php");
Is not sufficient to pass the $message variable to index.php.
As said in comments you can try
// file loginPDO.php
$message = '<label>Wrong Data</label>';
header("location:index.php?error=" . urlencode("Wrong Data"));
// file index.php
<?php
$message = isset($_GET['error']) ? $_GET['error'] : null; // get the error from the url
if(!empty($message)) {
echo '<label class="text-danger">'.$message.'</label>';
} ?>

PHP MySQL if date and time unavailable add to alert message

I am fairly new to PHP and a new student and so I will ask in advance to please forgive me if I have made errors that will be clearly obvious to someone experienced.
I am working on a page submission form that connects to a mysql database to either check for an existing value and if it does not exist then logs a string value of the datetime picker and also appends an id number to make a unique value to a table whenever someone was to press submit, and after form validation is accepted. Submitting if the record does not exist works and is ok.
However, whenever a record already exists, rather than displaying in the error message that the time is unavailable, the entire page just goes blank.
Initially, I had a button that would check to see if the record existed in the mysql table but I then decided it would be more efficient to try to include the date validation check of mysql table while completing the form validation and this is where I have trouble and of course the page breaks and nothing is displayed.
If someone could please guide me I would be most grateful.
it seems I am unable to add more code, but I will add what was wrong.
I did need to initialize $error=''; also $DateTime, and $id at the top of the script, I had it below but had forgotten to place it above and that was causing my problem.
<?php
$userid = "1";
$strid = strval($id);
$DateTimeCheck = $DateTime . $strid;
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$con->exec("SET CHARACTER SET utf8");
$sql = "SELECT booked FROM user_booking WHERE `booked` = :booked";
$sqlprep = $con->prepare($sql);
$ar_val = array(':booked' => $DateTimeCheck);
if (isset($_POST['datetime'])){
if (!$_POST['name']) {
$error = "<br/>- Please enter your name";
}
if (!$_POST['email']) {
$error .= "<br/>- Please enter your email";
}
if (!$_POST['message']) {
$error .= "<br/>- Please enter a message";
}
if (!$_POST['check']) {
$error .= "<br/>- Please confirm you are human";
}
if ($sqlprep->execute($ar_val)) {
while ($row = $sqlprep->fetch(PDO::FETCH_OBJ)) {
$DateTimeExists = $row->booked;
}
}
if (isset($DateTimeExists) && $DateTimeExists != ''){
$error .= "<br/>- The time you have requested is unavailable";
}
if ($error) {
$result = '<div class="alert alert-danger" role="alert"><strong>Whoops, there is an error</strong>. Please correct the following: ' . $error . '</div>';
} else {
mail("#gmail.com", "Contact message", "Name: " . $_POST['name'] . "
Email: " . $_POST['email'] . "
When: " . $_POST['datetime'] . "
Message: " . $_POST['message']);
{
$result = '<div class="alert alert-success" role="alert">Thank you, someone will be in touch soon to confirm your appointment. </div>';
$id = "$userid";
$strid = strval($id);
$DateTime = $_POST['datetime'];
$DateTimeCheck = $DateTime . $strid;
$strid = strval($id);
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user_booking ( user_id, booked ) VALUES ( :id, :booked )";
$q = $con->prepare($sql);
$q->execute(array(':booked' => $DateTime . $strid,
':id' => $id));
$con = null;
}
}
}
?>
Here is the markup for the form.
<form method="post" role="form">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Your name"
value="<?php echo $_POST['name']; ?>">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Your email"
value="<?php echo $_POST['email']; ?>">
</div>
<div class="form-group" align="left">
<label class="control-label">Date/Time</label>
<div class='input-group date' id='datetimepicker1'>
<input type='text' name="datetime" class="form-control" placeholder="desired time"
value="<?php echo $_POST['datetime']; ?>">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<textarea name="message" rows="5" class="form-control"
placeholder="message..."><?php echo $_POST['message']; ?></textarea>
</div>
<div class="checkbox" align="left">
<label class="readable" align="left">
<input type="checkbox" name="check"> I am human
</label>
</div>
<div align="left">
<input type="submit" name="submit" class="btn btn-success" value="Book Appointment!"/>
</div>
</form>
If you are using .= you need to first initialise the variable before .= will work on the variable.
You attempted to do that in this IF block
if (!$_POST['name']) {
$error = "<br/>- Please enter your name";
}
but if that error is not present you will never actually initialise the $error variable.
So the simple solution is to initialise $error before getting into this section of code
$error = '';
if (isset($_POST['datetime'])){
// So now you can change this test to use .=
if (!$_POST['name']) {
$error .= "<br/>- Please enter your name";
}
Now the variable will be testable later in the code
If this is in fact the problem here, you should have been getting errors reported. If you didnt see any then try adding these lines of code to any problem script while you test it
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

php oop check if user exists?

I want to display an error if a username exists, however no error is being thrown.
the function is on the User.php and im trying to display an error from that function.
i referenced this, however it is not relevant to the OOP way.
User.php
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$row['user_name'] == $username;
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Index.php
<?php
session_start();
require_once 'User.php';
$guest = new User();
if($guest->is_logged())
{
$guest->redirect('profile');
}
if (isset($_POST['btn_signup']) ){
$username = htmlentities($_POST['txt_username']);
$unpass = htmlentities($_POST['txt_password']);
$password = password_hash($unpass, PASSWORD_BCRYPT, ['cost' => 12] );
$unemail = $_POST['txt_email'];
$email = filter_var($unemail, FILTER_VALIDATE_EMAIL);
$guest = new User();
if($email == ""){
$errors[]= "Enter a Email";
}
if($username == ""){
$errors[]= "Enter a Username please";
}
if($password == ""){
$errors[]= "Enter a Password";
}
if($guest->check_user_exists($username)){
$errors[]= "Username Already Taken";
}
if($guest->signup($email,$password,$username)){
$guest->redirect('profile');
die('didnt redirect');
}
else{
$errors[]= "Invalid Entry";
}
}
$title = "Home";
require_once 'layouts/header.php';
?>
<div class="container">
<div class="row">
<div class="col-md-6">
<?php
if(isset($errors))
{
foreach($errors as $error)
{
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
}
}
else if(isset($_GET['joined']))
{
?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> Successfully registered <a href='index.php'>login</a> here
</div>
<?php
}
?>
<h1>Sign Up</h1>
<form action ="" method="POST">
<div class="form-group">
<label for="Email">Email address</label>
<input type="email" class="form-control" aria-describedby="emailHelp" name="txt_email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" aria-describedby="emailHelp" name="txt_username" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" class="form-control" aria-describedby="emailHelp" name="txt_password" placeholder="Enter password">
</div>
<button type="submit" name="btn_signup" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
return $stmt->fetchColumn() > 0; // fetchColumn return the number of rows selected
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Your function doesn't actually return or do anything. Return the result of fetch(), if it returns true - a result was found. If it returns false, there was no row matching the username. You don't need to check anything after that, as the fetch() method will only be true if a result was found.
Adjusted for that, your function would look like this
public function check_user_exists($username) {
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username' => $username));
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOExeception $e) {
echo $e->getMessage();
}
}
Also, its not a good idea to output errors directly (on a testing/development environment its fine, but on a live environment you should log it (error_log()) instead.
http://php.net/manual/en/pdostatement.fetch.php
public function ifUserAlreadyExist(string $email):bool{
$sql = "SELECT 1 FROM users WHERE email= :Email";
$statment = $this->conn->prepare($sql);
if (false === $statment) {
return false;
}
$statment->execute([':Email' => $email]);
return (bool)$statment->fetchColumn();
}
//You need to just select 1 object if is already exist and in this case function hint will be so handy, can set the function to boolean and see if it return true or false.
I hope I could help.

PDO Query not inserting in Database

The following code is created to register a user in my website. When I try to register a user the 'query' is being executed but the new record in the database is not shown.
The following code is the register form:
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="page-header">
<h2>Register Now</h2>
</div>
<div>
<form id="defaultForm" method="post" name="registerform" class="form-horizontal" action="index.php">
<div class="form-group">
<div class="col-lg-11">
<?php include('include/showErrors.php'); ?>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="username" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email address</label>
<div class="col-lg-5">
<input type="email" class="form-control" name="email" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Password</label>
<div class="col-lg-5">
<input type="password" class="form-control" name="password" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Age</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="age" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Sex</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="sex" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Country</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="country" autocomplete="off" />
</div>
</div>
<div class="form-group">
<div class="col-lg-8 col-lg-offset-3">
<button name="Submit" type="submit" class="btn btn-primary">Sign up</button>
</div>
</div>
<br>
</form>
</div>
</div>
The following is the doRegister user:
class Registration
{
private $dbCon = null;
public $regSuccessful = false;
public $verificationSuccess = false;
public $errors = array();
public $messages = array();
//the below function will automaticcaly start when a obejct of this class is created
public function __construct()
{
//session_start();
if(isset($_POST["Submit"]))
{
$this->registerUser($_POST['username'], $_POST['password'],$_POST['email'],$_POST['age'],$_POST['sex'],$_POST['country']);
}
else if (isset($_GET["id"]) && isset ($_GET["verification_code"]))
{
$this->verifyUser($_GET["id"], $_GET["verification_code"]);
}
}
//the following methods checks if a database connection is open or not
private function dbConnection()
{
if($this->dbCon != null)
{
return true;
}
else
{
//create database connection
try
{
$this->dbCon = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
return true;
} catch (PDOException $ex) {
$this->errors[] = MESSAGE_DATABASE_ERROR;
return false;
}
}
}
//the following method will handle and the registration errors
private function registerUser($username,$password,$email,$age, $sex,$country)
{
//this will remove extra spaces
$username = trim($username);
$email = trim($email);
$sex = trim($sex);
$country = trim($country);
if(empty($username))
{
$this->errors[] = MESSAGE_USERNAME_EMPTY;
}
else if(empty($password))
{
$this->errors[] = MESSAGE_PASSWORD_EMPTY;
}
else if(empty($country))
{
$this->errors[] = MESSAGE_COUNTRY_EMPTY;
}
else if(empty($sex))
{
$this->errors[] = MESSAGE_SEX_EMPTY;
}
else if(empty($age))
{
$this->errors[] = MESSAGE_AGE_EMPTY;
}
else if(strlen($password) < 6)
{
$this->errors[] = MESSAGE_PASSWORD_TOO_SHORT;
}
elseif (strlen($username) > 64 || strlen($username) < 2)
{
$this->errors[] = MESSAGE_USERNAME_BAD_LENGTH;
}
elseif (!preg_match('/^[a-z\d]{2,64}$/i', $username)) {
$this->errors[] = MESSAGE_USERNAME_INVALID;
} elseif (!preg_match('/^[a-z\d]{2,64}$/i', $country)) {
$this->errors[] = MESSAGE_COUNTRY_INVALID;
}
elseif (!preg_match('/^[a-z\d]{2,64}$/i', $sex)) {
$this->errors[] = MESSAGE_SEX_INVALID;
}
elseif (empty($email)) {
$this->errors[] = MESSAGE_EMAIL_EMPTY;
} elseif (strlen($email) > 64) {
$this->errors[] = MESSAGE_EMAIL_TOO_LONG;
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->errors[] = MESSAGE_EMAIL_INVALID;
}else if ($this->dbConnection())
{
// check if username or email already exists
$check_user_name = $this->dbCon->prepare('SELECT username, email FROM tbl_users WHERE username=:username OR email=:email');
$check_user_name->bindValue(':username', $username, PDO::PARAM_STR);
$check_user_name->bindValue(':email', $email, PDO::PARAM_STR);
$check_user_name->execute();
$result = $check_user_name->fetchAll();
// if username or/and email find in the database
// TODO: this is really awful!
if (count($result) > 0) {
for ($i = 0; $i < count($result); $i++) {
$this->errors[] = ($result[$i]['username'] == $username) ? MESSAGE_USERNAME_EXISTS : MESSAGE_EMAIL_ALREADY_EXISTS;
}
} else {
// check if we have a constant HASH_COST_FACTOR defined (in config/hashing.php),
// if so: put the value into $hash_cost_factor, if not, make $hash_cost_factor = null
//$hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
//the following will encrypt users password with the PHP 5.5's hash function
//$userPassHash = password_hash($password, PASSWORD_BCRYPT);
// $userPassHash = password_hash( $password, PASSWORD_BCRYPT, array(
// 'cost' => 12
// ));
//this will generate a random hash for email verification
$user_activation_hash = sha1(uniqid(mt_rand()), true);
//the following will write a new user data into the database
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now()), :age, :sex, :country');
$queryUserInsert->bindValue(':username', $username, PDO::PARAM_STR);
$queryUserInsert->bindValue(':userPassHash', $password, PDO::PARAM_STR);
$queryUserInsert->bindValue(':email', $email, PDO::PARAM_STR);
$queryUserInsert->bindValue(':user_activation_hash', $user_activation_hash, PDO::PARAM_STR);
$queryUserInsert->bindValue(':user_registration_ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$queryUserInsert->bindValue(':age', $age, PDO::PARAM_STR);
$queryUserInsert->bindValue(':sex', $sex, PDO::PARAM_STR);
$queryUserInsert->bindValue(':country', $country, PDO::PARAM_STR);
$queryUserInsert->execute();
//id of the new user registered
//$user_id = $this->dbCon->lastInsertId();
//checks if the query was succesfull, and send verification email
if($queryUserInsert)
{
$this->messages[] = MESSAGE_REGISTRATION_ACTIVATION_SUCCESSFUL;
}
else
{
$this->errors[] = MESSAGE_REGISTRATION_FAILED;
}
}
}
}
}
Screenshot of the Database:
Use this insert query:
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now(), :age, :sex, :country)');
You have added an extra ) after now() function in query; Put it after :country
Change
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now()), :age, :sex, :country');
^ Extra Closing Bracket ^ Closing Bracket For VALUES missing
To
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now(), :age, :sex, :country)');
Extra closing bracket in now()
Didn't closed bracket for VALUES.

Data within a bootstrap modal form doesn't transfer to a MySQL table using php

I have been working on this for some time now by looking at previous answers to questions, but still doesn't work.
I'm trying to get a MySQL table updated with the data in a Bootstrap Modal form when submitting via PHP. The php code below works when using it in a previous website (which doesn't use bootstrap).
The issue I get is on submit; the form passes the javascript validation and then opens the register.php file. When I look at the MySQL table the data hasn't transferred and the webpage is just blank with no content (url comes up as http://localhost/BootstrapEx/php/register.php).
Please can someone help as to why the data within the form doesn't transfer to MySQL when using Twitter Bootstrap and a way to fix this?
I know I have to change/update the security, validation and error pages within the php file, but at this stage all I want it to do is load the data into the MySQL table. I temporary created Thankyou.html, SystemError.html and RegError.html as you will see in the php code just to see if those pages opened.
Please find the code below:
Html: Just the modal form section
<div class="modal fade" id ="Register" role ="dialog">
<div class="modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<h4>Registration Screen</h4>
</div>
<div class ="modal-body">
<form name="myForm" role="form" action="php/register.php" method ="post" onsubmit="return validateForm()">
<fieldset>
<div class="form-group">
<label for="fname">First Name</label><span>*</span>
<input type="FirstName" class="form-control" id="fname" placeholder="Enter your first name" name="fname">
</div>
<div class="form-group">
<label for="lname">Last Name</label><span>*</span>
<input type="Surname" class="form-control" id="lname" placeholder="Enter your last name or surname" name="lname">
</div>
<div class="form-group">
<label for="email">Email address</label><span>*</span>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="psword1">Password</label><span>*</span>
<input type="password" class="form-control" id="psword1" placeholder="Password" name="psword1">
</div>
<div class="form-group">
<label for="psword2">Confirm Password</label><span>*</span>
<input type="password" class="form-control" id="psword2" placeholder="Confirm Password" name="psword2">
</div>
<div class = "form-group">
<a class = "btn btn-default" data-dismiss = "modal">Close</a>
<button class = "btn btn-primary" type="submit" name="submit" value="Yes">Register</button>
</fieldset>
</div>
</div>
</div>
</div>
</div>
</form>
register.php file (please excuse the error sections, these will be updated once the data submits into the table).
<?php
if(isset($_POST['submit']))
{
require ('php/mysqli_connect.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$errors = array(); // Initialize an error array.
// Check for a first name:
if (empty($_POST['fname']))
{
$errors[] = 'You forgot to enter your first name.';
} else
{
$fn = mysqli_real_escape_string($dbcon, trim($_POST['fname']));
}
// Check for a last name:
if (empty($_POST['lname']))
{
$errors[] = 'You forgot to enter your last name.';
} else
{
$ln = mysqli_real_escape_string($dbcon, trim($_POST['lname']));
}
// Check for an email address:
if (empty($_POST['email']))
{
$errors[] = 'You forgot to enter your email address.';
} else
{
$e = mysqli_real_escape_string($dbcon, trim($_POST['email']));
}
// Check for a password and match against the confirmed password:
if (!empty($_POST['psword1']))
{
if ($_POST['psword1'] != $_POST['psword2'])
{
$errors[] = 'Your two passwords did not match.';
} else
{
$p = mysqli_real_escape_string($dbcon, trim($_POST['psword1']));
}
} else
{
$errors[] = 'You forgot to enter your password.';
}
if (empty($errors))
{ // If everything's OK.
// Register the user in the database...
// Make the query:
$q = "INSERT INTO users (user_id, fname, lname, email, psword, registration_date) VALUES (' ', '$fn', '$ln', '$e', SHA1('$p'), NOW() )";
$result = #mysqli_query ($dbcon, $q); // Run the query.
if ($result)
{ // If it ran OK
header("Location:http://localhost/BootstrapEx/Thankyou.html");
echo '<p>Fields Loaded</p>';
exit();
} else
{ // If it did not run OK
// Error message:
header("Location:http://localhost/BootstrapEx/SystemError.html");
echo '<h2>System Error</h2>
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
//Debugging message:
echo '<p>' . mysqli_error($dbcon) . '<br><br>Query: ' . $q . '</p>';
} // End of if ($result)
mysqli_close($dbcon); // Close the database connection.
exit();
} else
{ // Report the errors
header("Location:http://localhost/BootstrapEx/RegError.html");
echo '<h2>Error!</h2>
<p class="error">The following error(s) occurred:<br>';
foreach ($errors as $msg) { // Echo each error
echo " - $msg<br>\n";
}
echo '</p><h3>Please try again.</h3><p><br></p>';
}// End of if (empty($errors))
} // End of the main Submit conditional
}
?>
MySQL php connection file (username, passwords etc details changed)
<?php
//This file provides the information for accessing the database and connecting to
//mysql. It also sets the language coding to utf-8.
DEFINE ('DB_USER', '****')
DEFINE ('DB_PASSWORD', '****')
DEFINE ('DB_HOST', 'localhost')
DEFINE ('DB_NAME', '****')
$dbcon = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die ('Could not connect to MySQL:' .mysqli_connect_error());
language encoding
mysqli_set_charset($dbcon, 'utf8');
?>
Javascript Validation
function validateForm() {
// First name validation
var w = document.forms["myForm"]["fname"].value;
var x = document.forms["myForm"]["lname"].value;
var y = document.forms["myForm"]["email"].value;
var z = document.forms["myForm"]["psword1"].value;
var b = document.forms["myForm"]["psword2"].value;
var atpos = y.indexOf("#");
var dotpos = y.lastIndexOf(".");
if (w == null || w == "") {
alert("First name must be filled out");
return false;
}
else if (/[^a-zA-z'-]/.test(w)) {
alert("First Name not completed, please only use letters & spaces with either (') or (-).");
return false;
}
// Last name validation
else if (x == null || x == "") {
alert("Last name must be filled out");
return false;
}
else if (/[^a-zA-z'-]/.test(w)) {
alert("Last name not completed, please only use letters & spaces with either (') or (-).");
return false;
}
// Email validation
else if (y == null || y == "") {
alert("Email address must be completed");
return false;
}
else if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=y.length) {
alert("Not a valid e-mail address");
return false;
}
// Password Validation
else if (z == null || z == "") {
alert("Password must be entered");
return false;
}
else if (z.length < 7 || !/[a-z]/.test(z) || !/[A-Z]/.test(z) || !/[0-9]/.test(z)) {
alert("Password must be a minimum of 8 characters, with at least 1 number, 1 lower case and 1 upper case letter.");
return false;
}
else if (z !== b) {
alert("Passwords do not match.");
return false;
}
}
Any help will be really appreciated.
Many thanks,
Hopeless coder
Syntax errors in your connection script:
$dbcon = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die ('Could not connect to MySQL:' .mysqli_connect_error());
language encoding
^^^^^^^^^^^^^^^^^
this is not valid PHP. Since you're just getting a blank page, you've probably got display_errors and error_reporting turned off. They should NEVER be off while developing/debugging. It's almost as bad as using the # suppression operator - the equivalent of stuffing your fingers in your ears and going "lalalalalala can't hear you".

Categories