JavaScript/Jquery file not loading - javascript

My Jquery works fine in-line however when I try and make it external it doesn't seem to work.
I have both scripts stored in the: include('./includes/header.html');
And I also have them stored at the root of the folder.
If any one could help would be great.
I have two links held within the header.html
<!DOCTYPE html>
<head>
<title> <?php $page_title ?> </title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="formValidation.js"></script>
<script src="jquery-1.10.2.js"></script>
</head>
<body>
<div id="wrapper">
<div id="header">
<h1>Films.com</h1>
</div>
<div id="content">
<div id="nav">
<ul>
<li>Login</li>
<li>Home</li>
<li>Register</li>
<li>Film</li>
<li>Add a Film</li>
</ul>
</div>
When going to add_film.php the Jquery that would normally slide down my form, now it doesn't slide down.
<?php
include('./includes/header.html');
echo "<h1>Add A film</h1>";
if(isset($_POST['submitted'])){
$errors = array(); // Initialize erroy array.
// Check for title.
if (empty($_POST['movie_title'])){
$errors[] = "You forgot to enter a title.";
} else {
$mn = (trim($_POST['movie_title']));
}
// Check for leading actor
if (empty($_POST['leading_actor'])){
$errors[] = "You forgot to enter the leading actor.";
} else {
$la = (trim($_POST['leading_actor']));
}
// Check for a rating
if (empty($_POST['rating'])){
$errors[] = "Please select a rating.";
} else {
$rating = ($_POST['rating']);
}
// Check for a review
if (empty($_POST['review'])){
$errors[] = "Please write a review";
} else {
$review = (trim($_POST['review']));
}
if (empty($errors)) { // If no errors were found.
require_once('./includes/Mysql_connect.php');
// Make the insert query.
$query = "INSERT INTO films (movie_title, actor, rating)
Values ('$mn', '$la', '$rating' )";
$result = mysql_query($query);
$id = mysql_insert_id();
$query = "INSERT INTO reviewed (review, movie_id)
values ('$review', '$id')";
$result = mysql_query($query);
//Report errors.
} else {
foreach ($errors as $msg){
echo " - $msg <br/> ";
}
}
}
?>
<html>
<form action="add_film.php" method="post" id="add_film">
<fieldset>
<label for="title">Movie Title</label>
<input type="text" name="movie_title" id="movie_title" />
<br/>
<br/>
<label for="actor">Leading Actor</label>
<input type="text" name="leading_actor" id="leading_name" />
<br/>
<br/>
<label for="rating">Rating</label>
<select id="rating" name="rating"/>
<option selected="selected" value=0 disabled="disabled">Select a Rating</option>
<option value="Terrible">Terrible</option>
<option value="Fair">Fair</option>
<option value="Ok">Ok</option>
<option value="Good">Good</option>
<option value="Excellent">Excellent</option>
</select>
<br/>
<br/>
<label for="review">Your Review</label>
<br/>
<textarea name="review" id="review" rows="15" cols="60"></textarea>
<br/>
<br/>
<input type="submit" name="submit" id="submit" value="submit" />
<input type="hidden" name="submitted" value="TRUE" />
</fieldset>
</form>
<br/>
</html>
<?php
include('./includes/footer.html');
?>
Here is my Jquery.
$(document).ready(function(){
$('#add_film').slideDown(800);
// Focus on first form field.
$("input:text:visible:first").focus();
$('#add_film').submit(function (e) {
var error = false;
// No value for movie_title
if ($('#movie_title').val() == "") {
alert("No Film");
error = true;
}
// No Value for actor
if ($('#leading_name').val() == "") {
alert("No actor");
error = true;
}
// No value for rating
if ($('#rating').val() == null) {
alert("No Rating");
error = true;
}
//No value for review
if ($('#review').val() == "") {
alert("No review");
error = true;
}
if (error) {
e.preventDefault();
}
});
});

Change the order you load them:
<script src="jquery-1.10.2.js"></script>
<script src="formValidation.js"></script>

the order in which you load the scripts is important.
since your script uses jquery, so jquery needs to be loaded before your script.
so change the order of loading. first load jquery, then your script.
this is also the reason, why your script works inline.

Related

Having Problem with my PHP Code and Jquery

I need some help
Whenever I input all the information and wanted to click submit, it always alert me "You already submit before" but it was the first time i entered the information. So there shouldn't be any duplicate values.
And the data itself also didn't post into my phpmyadmin database.
Secondly, i added the addclass("error") and removeclass ('error') in the javascript. However only those selection questions will show the red error border line while text input questions didn't show the error border line even though it is wrong
I have spent days to investigate it but still couldn't solve it.
My index.php file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Refund Request Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="css/style.css" >
<!-- <script src="form.js"></script>-->
</head>
<body>
<div class="container">
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="form-container">
<span style="text-align: center;padding-bottom: 0px;"><br>
<center>
<h1>
Refund Request Form
</h1>
</center>
</span>
<form method="post" id="form" name="form">
<label for="school_num">School Number: <span class="required">*</span></label>
<input id="school_num" type="text" placeholder="Enter your School Number" name="school_num" maxlength="50">
<label for="name">Full Name: <span class="required">*</span></label>
<input id="name" type="text" placeholder="Enter your Name in Capital as per IC" name="name" maxlength="50">
<label for="email">Email Address: <span class="required">*</span></label>
<input id="email" type="text" placeholder="Enter your Email Address" name="email" maxlength="50">
<label for="ic_num">IC Number: <span class="required">*</span></label>
<input id="ic_num" type="number" placeholder="Enter your IC Number (without dash)" name="ic_num" data-parsley-length="[12,12]" maxlength="12">
<label for="nts">Event1 Refund Amount: <span class="required">*</span></label>
<select id="nts" placeholder="-" name="nts" onchange="sum()" >
<option value = "-" selected>-</option>
<option value = "0" >0</option>
<option value = "80">80</option>
<option value = "100">100</option>
<option value = "110">110</option>
<option value = "110">120</option>
</select>
<label for="pesta">Event2 Refund Amount: <span class="required">*</span></label>
<select id="pesta" placeholder="" name="pesta" onchange="sum()" >
<option value = "-" selected>-</option>
<option value = "0" >0</option>
<option value = "100">100</option>
<option value = "360">360</option>
<option value = "450">450</option>
<option value = "460">460</option>
<option value = "535">535</option>
<option value = "540">540</option>
</select>
<label for="remarks">Remarks:</label>
<textarea id="remarks" name="remarks" placeholder="Type your remarks here" rows="5" maxlength="6000"></textarea>
<label style="border-bottom:1px dotted grey; padding-top: 30px;" colspan="2"></label>
<label for="refund" class="refund" style="color:#faa51a;font-family: 'Open Sans', sans-serif;font-weight: 500; font-size: 150%;width: 30%">Refund Total: </label>
<input id="refund" class="refund1" value="0" readonly style="border:none;color:#faa51a;font-family: 'Open Sans', sans-serif;font-weight: 500;font-size: 150%;width: 20%">
<!-- <input type="hidden" id="refund" name="refund" class="refund1" value="0" > -->
<input class="button-primary" name="submit" id="submit" role="button" type="button" onClick="validateForm()" value="Submit">
<!-- <input type="button" class="button-primary" type="submit" name="submit" id="submit" role="button" value="Submit">-->
</form>
<div id="success_message" style="display:none">
<h3>Submitted the form successfully!</h3>
<p> We will get back to you soon. </p>
</div>
<div id="error_message" style="width:100%; height:100%; display:none; "> <h3>Error</h3> Sorry there was an error sending your form.</div>
</div>
</div>
</body>
<script>
$(document).ready(function() {
//this calculates values automatically
sum();
$("#nts, #pesta").on("keydown keyup", function() {
sum();
});
});
function sum() {
var nts = document.getElementById('nts').value;
var pesta = document.getElementById('pesta').value;
var refundTotal = parseInt(nts) + parseInt(pesta);
if (!isNaN(refundTotal)) {
document.getElementById('refund').value ="RM " + refundTotal;
}
}
function validateEmail($email) {
var re = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if ($email == '' || !re.test($email))
{
return false;
}
}
function validateAlphabet($account_name){
var letters = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if($account_name.value.match(letters))
{
return true;
}
else
{
return false;
}
}
// function validateNumber (){
//
// }
function validateForm() {
$('#submit').disable=true;
var valid = true;
var error_msg="";
//school number
if($('#school_num').val()=='' && $.trim($('#school_num').val()).length<=0 ){
error_msg+=("Please insert your school number\n");
$('#school_num').addClass("error");
valid=false;
}else{
$('#school_num').removeClass("error");
}
//name
if($('#name').val()==''){
error_msg+=("Please insert your name\n");
$('#name').addClass("error");
valid=false;
}else{
$('#name').removeClass("error");
}
//email
if($('#email').val()==''){
error_msg+=("Please insert your email address\n");
$('#email').addClass("error");
valid=false;
}else{
if(validateEmail(document.getElementById('email').value)==false){
//console.log(document.getElementById('email').value);
error_msg+=("Invalid email address, Please fill in the correct email\n");
$('#email').addClass("error");
valid=false;
}else{
$('#email').removeClass("error");
}
}
//ic number
if($('#ic_num').val()==''){
error_msg+=("Please insert your IC Number (without dash)\n");
$('#ic_num').addClass("error");
valid=false;
}else{
if(!$.isNumeric($("#ic_num").val())){
//console.log(document.getElementById('email').value);
error_msg+=("Invalid IC Number - should be numbers only (no dash)\n");
$('#ic_number').addClass("error");
valid=false;
}else{
$('#ic_number').removeClass("error");
}
}
//school
if($('#school').val()=='-'){
error_msg+=("Please select your school\n");
$('#school').addClass("error");
valid=false;
}else{
$('#school').removeClass("error");
}
//nts
if($('#nts').val()=='-'){
error_msg+=("Please select your NTS refund amount\n");
$('#nts').addClass("error");
valid=false;
}else{
$('#nts').removeClass("error");
}
//pesta
if($('#pesta').val()=='-'){
error_msg+=("Please select your PESTA refund amount\n");
$('#pesta').addClass("error");
valid=false;
}else{
$('#pesta').removeClass("error");
}
if(error_msg!=""){
alert(error_msg);
}
if(valid){
$.ajax({
url: 'form_ajax.php',
type: 'POST',
data: {
'action':'check_duplicate',
'school_num':$('#school_num').val(),
'name':$('#name').val(),
'email':$('#email').val(),
'school':$('#school').val(),
'nts':$('#nts').val(),
'pesta':$('#pesta').val(),
'refund':$('#refund').val(),
},
error: function() {
},
before:function(){
},
dataType: 'json',
success: function(data) {
if(data.is_duplicated==0){
$.ajax({
url: 'form_ajax.php',
type: 'POST',
data: {
'action':'submit_form',
'school_num':$('#school_num').val(),
},
before:function(){
},
dataType: 'json',
success: function(data) {
$('#submit').disable=false;
if(data.status==1){
alert(data.message);
$('#success_message').show()
//TOOD: Clear all input
$('#school_num').val(''),
$('#name').val(''),
$('#email').val(''),
$('#school').val(''),
$('#nts').val(''),
$('#pesta').val(''),
$('#refund').val('')
}else{
alert(data.message);
$('#error_message').show()
}
},
error: function() {
},
});
//TOOD: Clear all input
$('#school_num').val(''),
$('#name').val(''),
$('#email').val(''),
$('#school').val(''),
$('#nts').val(''),
$('#pesta').val(''),
$('#refund').val('')
}
else{
alert('You already submit before');
}
},
});
}else{
$('#submit').disable=false;
}
}
</script>
</html>
My form_ajax.php file
<?php
//if(isset($_POST['submit'])){
if($_POST['action']=='submit_form'){
require "config.php";
require "common.php";
$statement=false;
$new_student = array(
"school_num" => $_POST['school_num'],
"name" => $_POST['name'],
"email" => $_POST['email'],
"ic_num" => $_POST['ic_num'],
"school" => $_POST['school'],
"nts" => $_POST['nts'],
"pesta" => $_POST['pesta'],
"remarks" => $_POST['remarks'],
"refund" => $_POST['refund']
);
try{
//#1 Open Connection
$connection = new PDO ($dsn,$username,$password,$options);
//#2 Prepare Sql QUERY
$statement = $connection->prepare("INSERT INTO details (school_num,name, email, ic_num,school,nts,pesta,remarks,refund,date) values (?,?,?,?,?,?,?,?,?,NOW())");
$statement ->bindParam(1,$_POST['school_num'],PDO::PARAM_STR);
$statement ->bindParam(2,$_POST['name'],PDO::PARAM_STR);
$statement ->bindParam(3,$_POST['email'],PDO::PARAM_STR);
$statement ->bindParam(4,str_replace($_POST['ic_num'], '-', ''),PDO::PARAM_INT);
$statement ->bindParam(5,$_POST['school'],PDO::PARAM_STR);;
$statement ->bindParam(6,$_POST['nts'],PDO::PARAM_INT);
$statement ->bindParam(7,$_POST['pesta'],PDO::PARAM_INT);
$statement ->bindParam(8,$_POST['remarks'],PDO::PARAM_STR);
$statement ->bindParam(9,$_POST['refund'],PDO::PARAM_INT);
//$statement = $connection->prepare($sql);
$statement->execute();
$return_message=array('status'=>1,'message'=>'Your information has been saved');
echo json_encode($return_message);
} catch (PDOException $error){
$return_message=array('status'=>0,'message'=>'Sorry we cannot save your information');
echo json_encode($return_message);
}
}
if( $_POST['action']=='check_duplicate'){
require "config.php";
require "common.php";
$statement=false;
try{
//#1 Open Connection
$connection = new PDO ($dsn,$username,$password,$options);
//#2 Prepare Sql QUERY
$statement = $connection->prepare("SELECT details.school_num FROM details");
$statement->bindParam(':school_num', $_POST ['school_num'], PDO::PARAM_STR);
//$statement = $connection->prepare($sql);
$statement->execute();
$statement->fetchAll();
$return_message=array('status'=>1,'message'=>'there is duplicate');
echo json_encode($return_message);
}catch (PDOException $error){
$return_message=array('status'=>0,'message'=>'no duplicate');
echo json_encode($return_message);
}
}
In your code php does not return the is_duplicated variable. Therefore, data.is_duplicated is always undefined in javascript. That's why result of if check if(data.is_duplicated==0) will always false, because undefined not equal to 0.
try to replace this code
$return_message=array('status'=>1,'message'=>'there is duplicate');
to this
$return_message=array('status'=>1,'message'=>'there is duplicate', 'is_duplicated' => 1);
and here
$return_message=array('status'=>0,'message'=>'no duplicate');
to this
$return_message=array('status'=>0,'message'=>'no duplicate', 'is_duplicated' => 0);
P.S.
By the way, why you don't check what statement has? I guess is not correct.
//$statement = $connection->prepare($sql);
$statement->execute();
$statement->fetchAll();
$return_message=array('status'=>1,'message'=>'there is duplicate');
echo json_encode($return_message);
should be
//$statement = $connection->prepare($sql);
$statement->execute();
$results = $statement->fetchAll();
if (empty($results)) {
$duplicate = 0;
} else {
$duplicate = 1;
}
$return_message=array('status'=>1,'message'=>'there is duplicate', 'is_duplicated' = $duplicate);
echo json_encode($return_message);
P.P.S.
To check if there is data in the database is better to use count() and limit=1
GOOD LUCK

PHP - run 1 insert query run twice record at the same time

addcustomer.php
<?php
include_once('functions.php');
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8s" />
<title>Add Customer</title>
<script type="text/javascript">
function CheckFields()
{
var cusname = document.getElementById("cusname").value;
var cusadd = document.getElementById("cusadd").value;
if(cusname == '')
{
alert("Please enter your customer name");
return false;
}
if(cusadd == '')
{
alert("Please enter your customer address");
return false;
}
return true;
}
</script>
</head>
<body onLoad="focus();add.name.focus()">
<?php
if(array_key_exists('submit_check', $_POST))
{
if($_POST['submit'] == 'Add')
{
if(!AddCustomer(trim($_POST['cusname']), trim($_POST['cusgender']), trim($_POST['cusadd'])))
{
echo "Add Customer Error, Please try it again later";
}
else
{
echo "Customer Information had been successfully added into the database";
}
}
}
else
{
AddCustomerForm();
}
?>
</body>
</html>
dbconnect.php
<?php
$host = "localhost";
$user = "root";
$passwd = "";
$dbname = "customertest";
?>
functions.php
<?php
include('dbconnect.php');
function AddCustomerForm()
{
?>
<form id="add" name="add" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<b><u>Customer Details</u></b><br />
<input type="hidden" name="submit_check" value="1" />
Customer Name : <input type="text" id="cusname" name="cusname" maxlength="50" /><br />
Gender : <input type="radio" name="cusgender" value="M" checked />Male
<input type="radio" name="cusgender" value="F" />Female<br /><br />
<b><u>Customer Address</u></b><br />
Address : <input type="text" id="cusadd" name="cusadd" maxlength="100" size="50" /><br /><br />
<input type="submit" name="submit" value="Add" onclick="return CheckFields();" />
<input type="reset" name="reset" value="Reset" />
</form>
<?php
}
function ConnectToDb()
{
global $host, $user, $passwd, $dbname;
#$db = mysql_pconnect($host, $user, $passwd);
if(!$db)
{
echo "Couldn't connect to the database";
exit;
}
mysql_select_db($dbname);
}
function AddCustomer($cusname, $cusgender, $cusadd)
{
ConnectToDb();
$query = "INSERT INTO customer (cusname, cusgender, cusjoindate) VALUES (\"".$cusname."\", '".$cusgender."', NOW())";
$result = mysql_query($query);
if($result)
{
$cusID = mysql_insert_id();
$query = "INSERT INTO customer_address (cusID, cusaddress) VALUES ('".$cusID."', '".$cusadd."')";
$result = mysql_query($query);
return 1;
}
else
{
return 0;
}
}
?>
From above code, when I fill in the customer form and click Add button, I get the double record in my database as shown as image below:
I really don't understand why the database store 2 records at the same time.
Am I writing wrong code? Can someone help me?
Did u assigned the Primary & FOREIGN KEY Properly. Means the cusID in the customer address table that refers the cusID(Primary key) in customer table.I'm tried the same as bellow it works fine.
ALTER TABLE customer_address ADD FOREIGN KEY (cusID) REFERENCES customertest.customer(cusID) ON DELETE RESTRICT ON UPDATE RESTRICT;

PHP + MYSQL instant search with radio button filtering

I have with the help of this guide https://www.youtube.com/watch?v=_AqM9U3mi9A created a working search form that displays instant search results (without having to press submit button) with PHP and MYSQL.
Then I wanted to filter the search results depending on what radio button is pressed. Now I also got this to work (partly with the help of this guide https://www.youtube.com/watch?v=DVS4qoB98U8) but ONLY when pressing submit on my search form. It does not work with instant search results for some reason, and that is my problem.
index.php (form):
<form class="form-custom" role="search" action="index.php" method="POST">
<div class="form-group">
<label for="all" class="radio-btn">
<input id="all" class="radio-custom" type="radio" name="searchfilter" value="all" checked="checked"> ALL
</label>
<label for="sports" class="radio-btn">
<input id="sports" class="radio-custom" type="radio" name="searchfilter" value="sports"> SPORTS
</label>
<label for="e-sports" class="radio-btn">
<input id="e-sports" class="radio-custom" type="radio" name="searchfilter" value="e-sports"> E-SPORTS
</label>
<label for="show-business" class="radio-btn">
<input id="show-business" class="radio-custom" type="radio" name="searchfilter" value="show-business"> SHOW BUSINESS
</label>
</div>
<div class="form-group">
<input type="text" name="search" autocomplete="off" class="form-control form-control-custom" placeholder="Search..." onkeyup="searchq();">
<button type="submit" name="submit" value="" class="btn btn-default btn-form-custom">Submit</button>
</div>
</form>
<div class="test" id="output">
<!-- this is where instant search results are supposed to appear -->
</div>
index.php (jquery - requiered for instant search results to work):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php",{searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}
</script>
search.php (PHP code):
<?php
include_once("connect.php");
$output = '';
if (isset($_POST['searchVal']) && isset($_POST['searchfilter']) && trim($_POST['searchVal']) != '' && strlen('searchVal') > 3 ){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
if($_POST['searchfilter'] == "all") {
$sqlCommand = "(SELECT * FROM sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM e_sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM show_business WHERE Title LIKE '%$searchq%')";
} else if($_POST['searchfilter'] == "sports") {
$sqlCommand = "SELECT * FROM sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "e-sports") {
$sqlCommand = "SELECT * FROM e_sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "show-business") {
$sqlCommand = "SELECT * FROM show_business WHERE Title LIKE '%$searchq%'";
}
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
if($count == 0){
$output .= '<p class="p-nof">No results found</p>';
}else{
$output .= '<ul ="dropdown">';
$output .= '<p>Search results: '.$count.'</p>';
while($row = mysql_fetch_array($query)){
$title = $row['Title'];
$url = $row['url'];
$id = $row['id'];
$output .= '<a class="searchresult" href="'.$url.'"><li> '.$title.'</li></a>';
}
$output .= '</ul>';
}
}
echo($output);
?>
Thanks in advance for any help!
EDIT:
I changed the javascript to the following:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchfilterVal: searchFilter}, function(output){
$("#output").html(output);
});
}
</script>
With this change the instant search results are working like before but the radio button filtering is not working. It seems that it's only using the data from the first radio input and ignoring the rest. When I click the other radio buttons it continues to use the data from the one listed first in the form. It does not change as I click.
I still need help with this! Thanks in advance!
Adjust your JS to post the value of searchFilter
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchFilter: searchfilter}, function(output){
$("#output").html(output);
});
}
</script>

Cannot Use Session Variable To Store Data

I have the a php file that contains the following
an html file which is used to collect data for a new user
php functions that validate the input data
javascript codes that alerts and prompt the user before data submission
after the validation process I want to move the input data to an insert.php to insert data into the database.
Below is the code
<?PHP
session_start();
if (!(isset($_SESSION['login_user']) && $_SESSION['login_user'] != '')) {
header ("Location: loginForm.php");
}
$hash;
$salt;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="layout.css">
<script language="javascript" type="text/javascript" src="/templates/myjavascript.js"></script>
<title>Title of the document</title>
<script>
window.onload=function(){
document.getElementById("new_user_form").onsubmit=function(){
if(this.pword.value === this.pword2.value)
{ alert("Are you sure you want to create a new user")
return true;}
else{ alert("Paswords must be the same ");
return false;}
}
}
</script>
</head>
<div>
<body>
<section id="content">
<form align="center" class="form" action="create_user.php" method="post" id="new_user_form" name="new_user_form">
<ul>
<li>
<h2>Please Fill The Form</h2>
</li>
<li>
<label for="username">User Name</label>
<input name="username" id="keyword" type="text" placeholder="type first name (required)" required />
</li>
<li>
<label for="pword">Password</label>
<input name="pword" id="pword" type="password" placeholder="########" required />
</li>
<li>
<label for="pword2">Confirm Password</label>
<input name="pword2" id="pword2" type="password" placeholder="########" required />
</li>
<p>
<input type = "reset" class="reset" name="submit"/>
<input type ="submit" name="submit" value="submit" class="submit" "/>
</p>
</section>
</ul>
</form>
</body>
</div>
<?php
/* php function to check pasword policy
The password has to be alphanumeric and special characters minimum 8 and max 16
*/
function checkpwdPolicy(){
if($_POST['pword'] === $_POST['pword2']) {
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{8,16}$/', $_POST['pword'])) {
echo '<script> alert(" password requirement not met"); </script>';
} else{
/* we use the session varible to store the hashed password and username */
/
$_SESSION['pwd'] = password_hash($_POST['pword'], PASSWORD_DEFAULT);
$_SESSION['username'] = $_POST['username'];
header ("Location: insert_user_table.php");
}
}
else {echo "passwords do not match "; }
}
//tis is used to call the fucntion that checks the password policy
if(isset($_POST['submit']) && isset($_POST['username']) && isset($_POST['pword']) && isset($_POST['pword2']) )
{checkpwdPolicy();}
?>
</html>
How ever when I run the cod I get the following error displayed.
Below is the error.
The question is how to move the data to the file that will do the insertion of data into database.
if you put any thing or show anything before session start command as well as before header("location: url"). it will not work.
simply
put "session_start();" top of the page.
dont show or use echo before header("Location: url");
another answer: header location not working in my php code
change your
<?PHP
to
<?php
remove spaces before it if any
session_start();
//remove this line
if (!(isset($_SESSION['login_user']) && $_SESSION['login_user'] != '')) {
//remove this line
header ("Location: loginForm.php");
//remove this line
}
remove spaces in between the above code.
or try this in place of your header
<script type="text/javascript">
window.location.assign('loginForm.php');
</script>
you need to start session at the beginning to avoid this warning message.
session_start();

Registration form not working and storing data in Database(PHP/MYSQL)

I trying to construct a registration page with PHP/MySQL ,first time when i tried to register as a new user it worked perfectly .after sometime time ,i checked once again with registration ,that page is not processing the data to the database .
the following code for registration page info as follows
please help me out
<?php
require_once("models/config.php");
if(isUserLoggedIn()) { header("Location: index.php"); die(); }
?>
<?php
//Forms posted
if(!empty($_POST))
{
$errors = array();
$email = trim($_POST["email"]);
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$confirm_pass = trim($_POST["passwordc"]);
//Perform some validation
//Feel free to edit / change as required
if(minMaxRange(5,25,$username))
{
$errors[] = lang("ACCOUNT_USER_CHAR_LIMIT",array(5,25));
}
if(minMaxRange(8,50,$password) && minMaxRange(8,50,$confirm_pass))
{
$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT",array(8,50));
}
else if($password != $confirm_pass)
{
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
if(!isValidemail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
//End data validation
if(count($errors) == 0)
{
//Construct a user object
$user = new User($username,$password,$email);
//Checking this flag tells us whether there were any errors such as possible data duplication occured
if(!$user->status)
{
if($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE",array($username));
if($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE",array($email));
}
else
{
//Attempt to add the user to the database, carry out finishing tasks like emailing the user (if required)
if(!$user->userPieAddUser())
{
if($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
if(count($errors) == 0)
{
if($emailActivation)
{
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
}
else {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
}
}
}
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration | <?php echo $websiteName; ?> </title>
<?php require_once("head_inc.php"); ?>
</head>
<body>
<div class="modal-ish">
<div class="modal-header">
<h2>Sign Up</h2>
</div>
<div class="modal-body">
<div id="success">
<p><?php echo $message ?></p>
</div>
<div id="regbox">
<form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p>
<label>Username:</label>
<input type="text" name="username" />
</p>
<p>
<label>Password:</label>
<input type="password" name="password" />
</p>
<p>
<label>Re-type Password:</label>
<input type="password" name="password" />
</p>
<p>
<label>Email:</label>
<input type="text" name="email" />
</p>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" name="new" id="newfeedform" value="Register" />
</div>
</form>
</div>
<div class="clear"></div>
<p style="margin-top:30px; text-align:center;">
Login / Forgot Password? / Home Page
</p>
</body>
</html>
also check your connection page properly..
add these kind of queries to your regrestration page..
mysql_query("insert into <your_table>(email,username,password) values('$email',' $username',' $password')");
Where exactly is the MySQL code? You've done your checks for the data but that's all it does. It is not being sent to a database. It's only being validated.

Categories