How to insert data into database only when input are not empty? - php

I came up with a problem which made me crazy as I am new to PHP. The problem is: the below timetable submission form works good on Chrome (every time I left the email unfilled, the submission cannot be processed). However, when using on safari, you can always submit blank form into the database.
Here is the html form.
<script type="text/javascript" src="/membership/my-form/js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="/membership/my-form/js/main.js"></script>
<form class="mf-form floating-labels" method="post" action="timetablesubmit.php">
<div>
<h1 style="text-align:center">Availability form</h1>
</div>
<div>
<p class="mf-select icon">
<select name="timetable-staff" class="user" required>
<option value="">Select Person</option>
<option value="AMY">Amy</option>
<option value="TOM">Tom</option>
</select>
</p>
<div>
<input name="location1" value="A" type="hidden">
<input name="location2" value="B" type="hidden">
</div>
<div class="AMY box">You work in A.</div>
<div class="TOM box">You work in B.</div>
</div>
<div class="icon">
<label class="mf-label" for="mf-email">Email Address</label>
<input class="email" type="email" name="timetable-email" id="mf-email" required>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
$( "select option:selected").each(function(){
if($(this).attr("value")=="Amy"){
$(".box").hide();
$(".AMY").show();
}
if($(this).attr("value")=="Tom"){
$(".box").hide();
$(".TOM").show();
}
});
}).change();
});
</script>
<style type="text/css">
.box{
padding: 10px;
display: none;
margin-top: 20px;
border: 1px solid #000;
font-size:1.6em;
text-align:center;
background-color: #f1f1f1;
}
</style>
Here is the timetablesubmit.php:
<?php
header("content-type:text/html;charset=utf-8");
session_start();
$timesubmit=date('Y-m-d H:i:s');
$staff=$_POST['timetable-staff'];
$email=$_POST['timetable-email'];
$con=mysql_connect("localhost","database","password");
if (!$con) {
die ('Could not connect:' . mysql_error());
}
mysql_select_db("database", $con);
mysql_query("set names utf8");
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
mysql_close($con);
sleep(2);
?>
<html>
<? require 'header.php'; ?>
<div class="tk-reg">
<p>Thak you <?php echo $_POST['timetable-staff']; ?><p>
<p> Time availability submitted successfully.<p>
Your email address is: <?php echo $_POST["timetable-email"]; ?>
</div>
<div class="tk-regfollow">
<ul style="text-align:center">
Back to home page.
</ul>
</div>
</html>
Then I searched the Internet and changed to below, still not working on Safari (the alert appears, however data still been insert into database.
<?php
require 'header.php';
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["timetable-staff"])) {
$nameErr = "Please select a staff.";
} else {
$staff = test_input($_POST["timetable-staff"]);
}
if (empty($_POST["timetable-email"])) {
$emailErr = "Email address is required";
} else {
$email = test_input($_POST["timetable-email"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con=mysql_connect("localhost","database_name","database_password");
if (!$con) {
die ('Could not connect:' . mysql_error());
}
mysql_select_db("database_name", $con);
mysql_query("set names utf8");
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
mysql_close($con);
sleep(2);
?>
<html>
<style>
.error {color: #FF0000;}
</style>
<h1 style="text-align:center">Availability form for
<?php
$d=strtotime("+1 Months");
echo date("M", $d) . " 2015 <br>";
?>
</h1>
<form class="mf-form floating-labels" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div>
<p class="mf-select icon">
<select name="timetable-staff" class="user" required>
<option value="">Select Person</option>
<option value="AMY">Amy</option>
<option value="TOM">Tom</option>
</select>
<span class="error">* <?php echo $nameErr;?></span>
</p>
</div>
<div class="icon">
<label class="mf-label" for="mf-email">Email Address</label>
<input class="email" type="email" name="timetable-email" id="mf-email" required>
<span class="error">* <?php echo $emailErr;?></span>
</div>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</html>
I hope someone could help me pointing out my mistakes. Thank you.
======================================================================
I tried a lot of ways to figure this out, however still have either 'this' or 'that' problems. I finally use a method that actually work, but I do not know whether it is not recommended.
Here is the code I modified in timetablesubmit.php
(my flow is: timetable.php ==>timetablesubmit.php==>welcome.php)
$email = trim($_POST['timetable-email']);
if($email !='' and $email !=null) {
$sql1;
}
else {
echo '<html><head>
<link rel="stylesheet" type="text/css" href="/membership/style.css"/>
<head>
<div class="check-error-message">
<p>Error: Email address is required.</p><br>
Return
</div>';
exit;
};

You can check with condition before insert operation
if($nameErr =="" && $emailErr == "")
{
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
}

you can have one condition here to avoid empty fill
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
here keep this condition like this
if($staff!='' && $email!='')
{
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
}

Html 5 "required" will not work in safari.
This line is the problem <input class="email" type="email" name="timetable-email" id="mf-email" required>
Write jquery/javascript validation to check the required field.
Hope its help you.

As they said, not all browsers accept the attribute required because it's new.
On PHP, server side, you can validate too if there's something filled with:
$var = trim($_POST['var']);
if(!is_empty($var)) {
//do mysqli function
}
else {
//show error
}
trim will remove blank spaces at start and end of the value given.
is_empty will be almost like $var == ""

Related

PHP code is showing in the webpage while executing

i am new to php I am trying to write a registration page.But something goes wrong.Every time i try to execute the code i get something like this in my page
Database details
Db name: cibil,
table name: table {id,username,password,email
}
query($sql)===true) { $_SESSION['message']='You are successfully added';
$_SESSION['username']=$user; $_SESSION['email']=$email;
header(location:page.php); } else{ $_SESSION['message']='Something went wrong'; } } ?>
My code is
<? php
session_start()
$_SESSION['message']='';
if($_SERVER['REQUEST_METHOD']=='POST')
{
$conn=new mysqli('localhost','root','','cibil') or die("error");
$user=$_POST['user'];
$pass=$_POST['pass'];
$email=$_POST['email'];
$sql="INSERT INFO table (username, password,email)VALUES('$user','$pass','$email')";
if($conn->query($sql)===true)
{
$_SESSION['message']='You are successfully added';
$_SESSION['username']=$user;
$_SESSION['email']=$email;
header(location:page.php);
}
else{
$_SESSION['message']='Something went wrong';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register form</title>
<link rel="stylesheet" type="text/css" href="reg_style.css">
</head>
<body>
<div id="h1">
<h1>Registration Page</h1>
</div>
<div id="err"><? php echo $_SESSION['message'] ?></div>
<div id='form'>
<form method="post" name='form' onsubmit="return rvalidate()" action="">
<p class="error">*Required</p>
<label for="user">Enter Your Name* : </label>
<input id="user" type="text" name="user" class="field">
<span class='error'></span><br><br>
<label for="email">Enter Your Email : </label>
<input id="email" type="text" name="email" class="field">
<br><br>
<label for="pass">Enter Your Password* : </label>
<input type="password" id="pass" name="pass" class="field"><span class='error'></span><br><br>
<label for="rpass">Re-Enter Your Password* : </label>
<input type="password" id="rpass" name="rpass" class="field"><span class='error'></span><br><br>
<input type="submit" id='submit' class="field" value="SUBMIT" onclick="validate();" >
</form>
</div>
<br><br>
<div id="login_text">
<b>If you are already register </b><br>Click here
</div>
<script type="text/javascript">
var error=document.getElementsByTagName('span');
var user=document.form.user;
var pass=document.form.pass;
var rpass=document.form.rpass;
function validate()
{
if(user.value==="")
{
error[0].innerHTML="*Enter Your name";
user.setAttribute("style","border-color:green");
}else{
error[0].innerHTML="";
user.setAttribute("style","border-color:initial");
}
if(pass.value=="")
{
error[1].innerHTML="*Password is Required";
pass.setAttribute("style","border-color:green");
}else{
error[1].innerHTML="";
pass.setAttribute("style","border-color:initial");
}
if(pass.value!==rpass.value)
{
error[2].innerHTML="*Password Missmatch";
rpass.setAttribute("style","border-color:green");
}else{
error[2].innerHTML="";
rpass.setAttribute("style","border-color:initial");
}
}
function rvalidate()
{
if (error[0].innerHTML=="" && error[1].innerHTML=="" && error[2].innerHTML=="") {
return true;
}
else{
return false;
}
}
</script>
</body>
</html>
Thank you for your help.........
Your code is not executed and shown as text because you have a space between ? and php at the start of the code. Try to start with <?php
session_start();. Then you will be able to debug all the rest :)
<div id="err"><? php echo $_SESSION['message']
If you notice there is a space between the ? And PHP, that may affect what is bring output. There is a few areas where your quotes don't match so if you check if the quotes aren't closing each other in places they shouldn't be closed then you should be okay
Is your filename correct? If it is a .htm or .html file it may not parse the PHP which could also be another issue you're having
You have a space at the opening of your php code :
<? php
should be :
<?php
Your code:
$sql="INSERT INFO table (username, password,email)VALUES('$user','$pass','$email')";
Must be without `...`:
$sql="INSERT INFO table (username, password,email)VALUES($user, $pass, $email)";

PHP to MYSQL form validation and database insertion with PHP_SELF and php process

I'm trying to use a php form saved on the artistRegister.php below and process it with the file at the bottom named processArtist.php .
I can't find the proper way to populate the fields in case there's an error and when I submit it to the database, I get an empty record on the database.
I'm populating a dropdown list on the navigation bar at header.php and using the same code to connect to the database, so it's not a database communication problem, since I'm able to create new empty records on the submit button press.
Tried several ways to make it work but would appreciate any help debugging the problem at hand.
Thank you advance.
***artistRegister.php***
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
//define page title
$title = 'Members Page';
//include header template
require('layout/header.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php if(isset($title)){ echo $title; }?></title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div class="container-fluid">
<div class="col-xs-3">
</div>
<div class="col-xs-6">
<?php
// define variables and initialize with empty values
$artistName = $artistLabel = $websiteAddress = $facebookAddress = $youtubeAddress ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["artistName"])) {
$nameErr = "Enter Artist name";
}
else {
$artistName = $_POST["artistName"];
}
if (empty($_POST["artistLabel"])) {
$labelErr = "Enter Label name";
}
else {
$artistLabel = $_POST["artistLabel"];
}
}
?>
<form class="form" method="POST" action="processArtist.php">
<div class="form-group">
<label for="artistName">Artist Name:</label>
<input type="text" class="form-control" id="artistName" value="<?php echo htmlspecialchars($artistName);?>">
<span class="error" style="color: red"><?php echo $nameErr;?></span><br>
<label for="artistLabel">Artist Label:</label>
<input type="text" class="form-control" id="artistLabel" value="<?php echo htmlspecialchars($artistLabel);?>">
<span class="error"><?php echo $LabelErr;?></span><br>
<label for="websiteAddress">Artist Website:</label>
<input type="text" class="form-control" id="websiteAddress" value="<?php echo htmlspecialchars($websiteAddress);?>">
<label for="facebookAddress">Artist Facebook:</label>
<input type="text" class="form-control" id="facebookAddress" value="<?php echo htmlspecialchars($facebookAddress);?>">
<label for="youtubeAddress">Artist Youtube:</label>
<input type="text" class="form-control" id="youtubeAddress" value="<?php echo htmlspecialchars($youtubeAddress);?>">
<br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
<div class="col-xs-3">
</div>
</div>
</body>
***processArtist.php***
<?php
$host="localhost";
$username="some_user_with_access";
$password="the_user_password";
$db_name="artist_management";
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump($_POST);
$artistName=$_POST['artistName'];
$artistLabel=$_POST['artistLabel'];
$websiteAddress=$_POST['websiteAddress'];
$facebookAddress=$_POST['facebookAddress'];
$youtubeAddress=$_POST['youtubeAddress'];
$sql="INSERT INTO artists (artistName, artistLabel, websiteAddress, facebookAddress, youtubeAddress)
VALUES
('$artistName', '$artistLabel', '$websiteAddress', '$facebookAddress', '$youtubeAddress')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);

Datepicker Date format insert and 0000-00-00

I have searched on the above topic and found various answers but didn't help me out
whenever I post a date on from ny web form, the result on my table is always 0000-00-00
I have been at this for 2 days and tried all suggestions i found but to no avail. i am sure i'm missing a very tiny detail. here are my codes:
<html>
<head>
<meta charset="utf-8">
<title>IBADAM BMs</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
});
</script>
</head>
<body bgcolor="#E6E6FA">
<br>
<div>
<div style="float: left; margin-left: 340px;>
<img src="../image/banner.png" alt="" align=""/>
</div>
<br><br><br><br><br>
<div style="float: left; margin-left: 1100px; margin-top: 0px;">
Log out
</div>
<br><br>
<center><b><h3>DIVISION</h3></b></center>
<?php
error_reporting (E_ALL ^ (E_NOTICE + E_WARNING));
$con=mysqli_connect("localhost","alagbeco","a12345","alagbeco_modem");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(!isset($_POST['submit'])) {
?>
<center>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<br><br>
Branch:
<select name="branch">
<option></option>
<option>DIVINE</option>
<option>GLORY 1</option>
<option>GLORY 2</option>
</select>
<br><br>
Date:
<input type="text" name="datepicker" id="datepicker">
<br><br>
Amount:
<input type="text" name="amount">
<br><br>
<input type="submit" name = "submit" value ="Process">
</form>
</center>
<?php
} else {
// escape variables for security
$branch = $_POST['branch'];
$amount = $_POST['amount'];
$datepicker = $_POST['date'];
//check for existence
$check_sql = "SELECT count(no) FROM bm_ibadan_division WHERE branch= '$branch' AND date = '$datepicker'";
$check = mysqli_query($con,$check_sql);
while ($check_rsult = mysqli_fetch_array($check)) {
$count = $check_rsult['count(no)'];
if($count >0 ) {
die ("Double treatment not allowed");
} else {
//insert into table
$sql = "INSERT INTO bm_ibadan_division (branch, status, amount, date)
VALUES ('$branch', 'Reconciled', '$amount', '$datepicker')";
$result = mysqli_query($con, $sql);
} echo '<br><br><center>Entry Successful</center><br><br>';
}
}
?>
<br>
</body>
</html>
Formate should be yy-mm-dd.Try like this:
<script>
$(function() {
$("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
});
</script>
also change: $datepicker = $_POST['date']; to $datepicker = $_POST['datepicker'];
date format has to be YYYY-MM-DD
<script>
$(function() {
$("#datepicker").datepicker({dateFormat: 'yyyy-mm-dd'});
});
</script>
Either change this
<input type="text" name="datepicker" id="datepicker">
to
<input type="text" name="date" id="datepicker">
OR
Change
$_POST['date']
to
$_POST['datepicker']
In your php code
$datepicker=$_POST['date'] like this.
Please Change to $_POST['datepicker']. Then it will works.Thanks
I also faced this problem and I used following code:
date('Y-m-d', strtotime(str_replace('/', '-', $_POST['date'])))

select option dropdown hidden input validation

In the below code: i have a select option dropdown(Employed,UmEmployed) If i select Option Employed it shows some input field(Current Designation, Current CTC) if i submit data without inserting anything it show validation: current designation is required.
If i select another option from dropdown that is unemployed it should redirect to another page directly but its not going to success.php (unemployed) that one is also validating.
<html>
<head>
<style>
#employer
{
display:none;
}
.error
{
color:#F00;
}
</style>
<?php
$currentdes="";
$currentdesErr="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
if(empty($_POST["desig"]))
{
$currentdesErr="* Current Designation is Required";
$valid=false;
echo "<style>#employer{display:block;}</style>";
}
else
{
$currentdes=test_input($_POST["desig"]);
}
//if valid then redirect
if($valid){
include 'database.php';
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=success.php">';
exit;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<form id="jsform" method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>Chose Your Browser: <select name = "currentsta" required>
<option value = "">-- Select an Option --</option>
<option value = "1" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "1") echo "selected"; ?>>Employed</option>
<option value = "2" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "2") echo "selected"; ?>>UnEmployed</option>
</select>
</p>
<div id="employer">
Current Designation: <label><input type="text" name="desig" size="50" /></label>
<span class="error"><?php echo $currentdesErr?></span>
<br>
Current CTC: <label><input type="text" size="50" /></label><br>
</div>
<!--currentstatus starts here-->
<script type="text/javascript">
$('p select[name=currentsta]').change(function(e){
if ($('p select[name=currentsta]').val() == '1'){
$('#employer').show();
}else{
$('#employer').hide();
}
});
</script>
<!--currentstatus Ends here-->
<!--Submit Button-->
<input type="button" value = "Submit" onClick=" document.getElementById('jsform').submit();" />
</form>
</body>
</html>
The desig input field will be empty for unemployed option as it is not being filled. Hence you should consider both the conditions. Also don't include database.php in the if block . Instead inside the success.php
<html>
<head>
<style>
#employer
{
display:none;
}
.error
{
color:#F00;
}
</style>
<?php
$currentdes="";
$currentdesErr="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
if(empty($_POST["desig"]) && $_POST["currentsta"]==1)
{
$currentdesErr="* Current Designation is Required";
$valid=false;
echo "<style>#employer{display:block;}</style>";
}
else
{
$currentdes=test_input($_POST["desig"]);
}
//if valid then redirect
if($valid){
//include 'database.php';
header('Location:success.php');
exit;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<form id="jsform" method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>Chose Your Browser: <select name = "currentsta" required>
<option value = "">-- Select an Option --</option>
<option value = "1" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "1") echo "selected"; ?>>Employed</option>
<option value = "2" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "2") echo "selected"; ?>>UnEmployed</option>
</select>
</p>
<div id="employer">
Current Designation: <label><input type="text" name="desig" size="50" /></label>
<span class="error"><?php echo $currentdesErr?></span>
<br>
Current CTC: <label><input type="text" size="50" /></label><br>
</div>
<!--currentstatus starts here-->
<script type="text/javascript">
$('p select[name=currentsta]').change(function(e){
if ($('p select[name=currentsta]').val() == '1'){
$('#employer').show();
}else{
$('#employer').hide();
}
});
</script>
<!--currentstatus Ends here-->
<!--Submit Button-->
<input type="button" value = "Submit" onClick=" document.getElementById('jsform').submit();" />
</form>
</body>
</html>
If on selection of unemployed option, you want to redirect to another page, then redirect it using JavaScript.
In the script at the end of the page, the modification would be -
$('p select[name=currentsta]').change(function(e){
if ($('p select[name=currentsta]').val() == '1'){
$('#employer').show();
}else{
//$('#employer').hide();
//This redirects to next page on selecting the option.
window.location.href= "success.php";
}
});

php, mysql, javascript dropdown list

I am new to coding and have no clue. I managed to grap this script from this site http://www.99points.info/2010/12/n-level-dynamic-loading-of-dropdowns-using-ajax-and-php/
I amended the titles and field inputs to match my project requirements instead of the ones used in the demo. I managed to get this working on my project with reference to the drop down lists.
The problem i am having now is how do you make the script accept the values and input it into the database after the customer selects the drop down lists and clicks the submit button.
If there is a better way to rewrite these codes?
Please i am in need of help. Thank you!
here is the code i got on the "get_child_categories.php" file:
<?php
include('cn.php');
if($_REQUEST)
{
$id = $_REQUEST['parent_id'];
$query = "select * from tour where pid = ".$id;
$results = #mysql_query( $query);
$num_rows = #mysql_num_rows($results);
if($num_rows > 0)
{?>
<select name="sub_category" class="parent">
<option value="" selected="selected">-- Sub Category --</option>
<?php
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['tour_id'];?>"><?php echo $rows
['category'];?></option>
<?php
}?>
</select>
<?php
}
else{echo '<label style="padding:7px;float:left; font-size:12px;">No Record Found
!</label>';}
}
?>
Also note that the "No Record Found" is always displayed after selecting all drop down lists at the end. How do i fix this to show every criteria is met before submission?
This is the "booking.php" form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link href="style.css" rel="stylesheet" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Jurassic Tours/booking form</title>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.livequery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//$('#loader').hide();
$('.parent').livequery('change', function() {
$(this).nextAll('.parent').remove();
$(this).nextAll('label').remove();
$('#show_sub_categories').append('<img src="loader.gif" style="float:left;
margin-top:7px;" id="loader" alt="" />');
$.post("get_chid_categories.php", {
parent_id: $(this).val(),
}, function(response){
setTimeout("finishAjax('show_sub_categories', '"+escape(response
)+"')", 400);
});
return false;
});
});
function finishAjax(id, response){
$('#loader').remove();
$('#'+id).append(unescape(response));
}
</script>
<style>
.both h4{ font-family:Arial, Helvetica, sans-serif; margin:0px; font-size:14px;}
#search_category_id{ padding:3px; width:200px;}
.parent{ padding:3px; width:150px; float:left; margin-right:12px;}
.both{ float:left; margin:0 0px 0 0; padding:0px;}
</style>
</head>
<?php
include('cn.php');?>
<body>
<div id="main">
<div id="header">
<img src="images/banner.jpg" alt="Banner" style="padding:10px"/>
</div>
<div id="mylinks">
<div id="navcontainer">
<ul>
<li>Home</li>
<li>Login</li>
<li>Register</li>
<li>Booking</li>
<li>About Us</li>
<li>Services</li>
<li>Feedback</li>
<li>Agency Login</li>
<li>Logout</li>
</div>
</div>
<div id="content">
<h2><center>PLEASE PLACE YOUR BOOKING</center></h2>
<div style="padding-left:30px; height:710px;">
<br clear="all" /><br clear="all" />
<form action="booking.php" method="post">
<div id="show_sub_categories">
<select name="search_category" class="parent">
<option value="" selected="selected">-- Categories --</option>
<?php
$query = "select * from tour where pid = 0";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['tour_id'];?>"><?php echo $rows
['category'];?></option>
<?php
}?>
</select>
</div>
<br clear="all" /><br clear="all" />
<input type="submit" name="submit" value="submit">
</form>
<br clear="all" /><br clear="all" />
</div>
</body>
</html>
The booking form is getting data from the tour table in the database where there is tour,destination,and duration all dependant on drop down lists selected.
This is the processing part where i do not know how to do after the submit button is pressed so i left it blank! The only data i can recover is the Primary key from the customer table as shown below.
<?php
//When submit button is pressed.
if (isset($_POST['submit'])) {
//Include the server and database connection.
include('cn.php');
session_start();
$userUsername = $_SESSION['loggedInUser'];
// Build the SQL query to retreive the variables ($) and input the data into the database.
$sql = "INSERT INTO booking
(user_id)
VALUES ((SELECT user_id FROM user WHERE user_username =
'" . $userUsername . "'))";
// test the sql statement.
if(!mysql_query($sql,$cn)) {
die(mysql_error($cn));
}
// direct to this page when booking is successful.
header('Location: booking_success.php');
}
?>
I forgot to include the update.php file
<?php
if (!empty($_GET['tour_id']) && !empty($_GET['value'])) {
$id = $_GET['tour_id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=jurassicbase', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `categories`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
$out[] = '<option value="'.$row['tour_id'].'">'.$row
['name'].'</option>';
}
echo json_encode(array('error' => false, 'list' => implode('', $out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
I'm guessing you are never reaching the form processor as you don't have any <form> tag in your form page.
You would need:
<form action="your_form_processor.php" method="post">
// your form fields
</form>
to get that to work.
Apart from that you need to switch to PDO (or mysqli) and prepared statements as your code is vulnerable to sql injection.
While you are developing your code, you should also remove all # error suppressing operators.

Categories