Issue in hobbies, as unable to get selected values using PHP - php

I have provided pre tag at the top so that i can see what values are going when i click on ragister button, all values are going correct except hobbies as its giving "on" why this so, please let know and I am new to php please explain me in detail as much as you can.
<?php
$error_array = array();
$fname = $lname = $email = $dob = $Mchecked = $Fchecked = $hobbies ="";
if(isset($_POST["sbt_save"]))
{
echo '<pre>'; print_r($_POST); echo "</pre>";
if($_POST['fname']=="")
{
$err ="Please Enter your first name"."<br>";
array_push($error_array,$err);
}
else
{
$fname = test_input($_POST['fname']);
}
if($_POST['lname']=="")
{
$err ="Please Enter your last name"."<br>";
array_push($error_array,$err);
}
else
{
$lname = test_input($_POST["lname"]);
}
if($_POST['email']=="")
{
$err ="Please Enter your email"."<br>";
array_push($error_array,$err);
}
else
{
$email = test_input($_POST["email"]);
}
if($_POST['dob']=="")
{
$err ="Please Enter your date of birth"."<br>";
array_push($error_array,$err);
}
else
{
$dob = test_input($_POST["dob"]);
}
if(!isset($_POST["gender"]))
{
$err ="Please select gender"."<br>";
array_push($error_array,$err);
}
else
{
$gender = $_POST["gender"];
if ($gender == "Male")
{
$Mchecked = "checked";
}
else if ($gender == "Female")
{
$Fchecked = "checked";
}
}
if(!isset($_POST['hobbies']))
{
$err ="Please Enter your hobbies"."<br>";
array_push($error_array,$err);
}
else
{
$hobbies = test_input($_POST['hobbies']);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ragistration Form</title>
<link rel="stylesheet" type="text/css" href="ragistration_form.css">
<script src="jquery-2.2.1.min.js"></script>
<script>
/*
$(document).ready(function(event)
{
$(".sbt_button").click(function(event)
{
var error_arr = [];
var email_value = $("#email").val();
var position_of_at = email_value.indexOf('#');
var position_of_dot = email_value.lastIndexOf('.');
if($("#fname").val() == null || $("#fname").val() == "")
{
var err = "First Name";
error_arr.push(err);
}
if($("#lname").val() == null || $("#lname").val() == "")
{
var err = "Last Name ";
error_arr.push(err);
}
if(position_of_at == -1 || position_of_dot == -1 || (position_of_at + 2) >= position_of_dot )
{
var err = "Email ";
error_arr.push(err);
}
if($("#dob").val() == null || $("#dob").val() == "")
{
var err = "Date of Birth ";
error_arr.push(err);
}
if(!$("input[type='radio']").is(":checked"))
{
var err = "Gender ";
error_arr.push(err);
}
if(!$("input[type='checkbox']").is(":checked"))
{
var err = "Hobbies ";
error_arr.push(err);
}
if(error_arr.length !=0)
{
event.preventDefault();
alert(error_arr);
}
});
});
*/
</script>
</head>
<body>
<form class="form" name="myForm" action="" method="post">
<table>
<tr>
<p class="heading">Ragistration Form</p>
</tr>
<?php
if($error_array !="")
{
foreach($error_array as $value)
{
echo "<tr><td> ". $value. "</td></tr>";
}
}
?>
<tr>
<td class="field_Name">First Name :<b style="color:red">*</b></td>
<td><input type="text" name="fname" id="fname" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Last Name :<b style="color:red">*</b></td>
<td><input type="text" name="lname" id="lname" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Email :<b style="color:red">*</b></td>
<td><input type="text" name="email" id="email" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Date of Birth :<b style="color:red">*</b></td>
<td><input type="date" name="dob" id="dob" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Gender :<b style="color:red">*</b></td>
<td><input type="radio" name="gender" value="Male"class="inputfield_Name" <?php echo $Mchecked;?>/>Male
<input type="radio" name="gender" value="Female" <?php echo $Fchecked;?> />Female</td>
</tr>
<tr>
<td class="field_Name">About Yourself :</td>
<td><textarea name="abt" class="inputfield_Name"$></textarea></td>
</tr>
<tr>
<td class="field_Name">Hobbies :<b style="color:red">*</b></td>
<td><input name="hobbies" type="checkbox" id="hobbies" class="inputfield_Name" />Cricket
<input name="hobbies" type="checkbox" />Singing
<input name="hobbies" type="checkbox" />Travling</td>
<tr>
<td></td>
<td>
<input name="hobbies" type="checkbox" class="inputfield_Name"/>Writing
<input name="hobbies" type="checkbox" />Teaching
<input name="hobbies" type="checkbox" />Driving
</td>
</tr>
<tr>
<td>
</td>
<td><input type="submit" value="Ragister" name="sbt_save" class="sbt_button"/></td>
</td>
</tr>
</table>
</form>
</body>
</html>

You need to add value attributes to the checkbox elements:
<tr>
<td class="field_Name">Hobbies :<b style="color:red">*</b></td>
<td><input name="hobbies" value="cricket" type="checkbox" id="hobbies" class="inputfield_Name" />Cricket
<input name="hobbies" value="singing" type="checkbox" />Singing
<input name="hobbies" value="travelling" type="checkbox" />Travling</td>
<tr>
<td></td>
<td>
<input name="hobbies" value="writing" type="checkbox" class="inputfield_Name"/>Writing
<input name="hobbies" value="teaching" type="checkbox" />Teaching
<input name="hobbies" value="driving" type="checkbox" />Driving
</td>
</tr>

Related

Lost PHP variable, last seen in Chrome, answers to the name $quote_date

I can't seem to find my PHP variable $quote_date. I have a form that grabs job records from the database and displays a job's current progress in the form ready to be edited, submitted and updated to the database. All of the job's other records are being collected and displayed correctly but the $quote_date is missing in action. Yet when I echo the $quote_date after the renderForm() function is executed it appears to really exist, at least at that point. Why is the $quote_date not being displayed in the form?
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Allow the user to both create new records and edit existing records.
// Connect to the database.
$connect = mysqli_connect('localhost', 'username', 'password', 'database');
if ( !$connect ) {
die( 'connect error: '.mysqli_connect_error() );
}
// creates the new/edit record form.
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($error = '', $id = '', $start_date = '', $company = '', $stock_code = '', $card_quantity = '', $fiske_print = '', $carrier_quantity = '', $quoted = '', $quote_details = '', $quoted_date = '', $quote_accepted = '', $quote_accepted_date = '', $proof_sent = '', $proof_sent_date = '', $proof_approved = '', $proof_approved_date = '', $printed = '', $print_date = '', $closed_loop_allocated = '', $invoiced = '', $invoiced_date = '', $posted = '', $tracking_number = '', $postal_date = '', $paid = '', $is_bulk_load = '', $bulk_funds_recieved = '', $cards_loaded = '', $notes = '', $completed = '')
{
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<?php
$pageName = 'overview';
?>
<?php
include('header.php');
?>
<h1><?php
if ($id != '') {
echo "Edit Record";
} else {
echo "New Record";
}
?></h1>
<?php
if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error . "</div>";
}
?>
<form action="" method="post">
<div>
<table>
<tr>
<td colspan="2" style="text-align:center;"><strong>Job Details</strong></td>
<td colspan="2" style="text-align:center;"><strong>Job Progress</strong></td>
</tr>
<tr>
<td>ID: </td>
<td><input type="text" name="id" value="<?php echo $id; ?>" readonly></td>
<td>Quoted: </td>
<td><input type="checkbox" name="quoted" value="1" <?php if($quoted == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Start Date: </td>
<td><input type="date" name="start_date" value="<?php if($start_date !== ''){echo date('Y-m-d',strtotime($start_date));} ?>"></td>
<td>Quote Details: </td>
<td><input type="text" name="quote_details" size="40" value="<?php echo $quote_details; ?>"></td>
</tr>
<tr>
<td>Company: </td>
<td><input type="text" name="company" size="40" value="<?php echo $company; ?>"></td>
<td>Quote Date: </td>
// Here is where the mystery lies why is my $quote_date variable missing?
<td><input type="date" name="quote_date" value="<?php echo date('Y-m-d',strtotime($quote_date)); ?>"></td><?php echo '<script type="text/javascript">alert("'.$quote_date.'");</script>'; ?>
</tr>
<tr>
<td>Stock Code: </td>
<td>
<div id="billdesc">
<select id="test" name="stock_code">
<option class="non" value="GS01">GS01</option>
<option class="non" value="GS03">GS03</option>
<option class="non" value="SM01">SM01</option>
<option class="non" value="SM11">SM11</option>
<option class="non" value="CG01">CG01</option>
<option class="non" value="CG38">CG38</option>
<option class="editable" value="Other">Other</option>
</select>
<input class="editOption" style="display:none;" placeholder="Text juaj"></input>
</div>
</td>
<td>Quote Accepted: </td>
<td><input type="checkbox" name="quote_accepted" value="1" <?php if($quote_accepted == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Card Quantity: </td>
<td><input type="text" name="card_quantity" value="<?php echo $card_quantity; ?>"></td>
<td>Quote Accepted Date: </td>
<td><input type="date" name="quote_accepted_date" value="<?php if($quote_accepted_date !== ''){echo date('Y-m-d',strtotime($quote_accepted_date));} ?>"></td>
</tr>
<tr>
<td>Carrier Quantity: </td>
<td><input type="text" name="carrier_quantity" value="<?php echo $carrier_quantity; ?>"></td>
<td>Proof Sent: </td>
<td><input type="checkbox" name="proof_sent" value="1" <?php if($proof_sent == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Fiske Print: </td>
<td><input type="checkbox" name="fiske_print" value="1" <?php if($fiske_print == 1){echo 'checked';} ?>></td>
<td>Proof Sent Date: </td>
<td><input type="date" name="proof_sent_date" value="<?php if($proof_sent_date !== ''){echo date('Y-m-d',strtotime($proof_sent_date));} ?>"></td>
</tr>
<tr>
<td rowspan="6" colspan="2" style="text-align:center;">
Notes:<br>
<textarea name="notes" rows="8" cols="70"><?php echo $notes; ?></textarea>
</td>
<td style="text-align:right;">Proof Approved: </td>
<td style="text-align:left;"><input type="checkbox" name="proof_approved" value="1" <?php if($proof_approved == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Proof Approved Date: </td>
<td><input type="date" name="proof_approved_date" value="<?php if($proof_approved_date !== ''){echo date('Y-m-d',strtotime($proof_approved_date));} ?>"></td>
</tr>
<tr>
<td>Printed: </td>
<td><input type="checkbox" name="printed" value="1" <?php if($printed == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Print Date</td>
<td><input type="date" name="printed_date" value="<?php if($print_date !== ''){echo date('Y-m-d',strtotime($print_date));} ?>"></td>
</tr>
<tr>
<td>Closed Loop Allocated: </td>
<td><input type="checkbox" name="closed_loop_allocated" value="1" <?php if($closed_loop_allocated == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Invoiced: </td>
<td><input type="checkbox" name="invoiced" value="1" <?php if($invoiced == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Paid: </td>
<td><input type="checkbox" name="paid" value="1" <?php if($paid == 1){echo 'checked';} ?>></td>
<td>Invoice Date: </td>
<td><input type="date" name="invoice_date" value="<?php if($invoice_date !== ''){echo date('Y-m-d',strtotime($invoice_date));} ?>"></td>
</tr>
<tr>
<td>Is Bulk Load: </td>
<td><input type="checkbox" name="is_bulk_load" value="1" <?php if($is_bulk_load == 1){echo 'checked';} ?>></td>
<td>Posted: </td>
<td><input type="checkbox" name="posted" value="1" <?php if($posted == 1){echo 'checked';} ?>></td>
</tr>
<tr>
<td>Bulk Funds Recieved</td>
<td><input type="checkbox" name="bulk_funds_recieved" value="1" <?php if($bulk_funds_received == 1){echo 'checked';} ?> ></td>
<td>Postal Date: </td>
<td><input type="date" name="postal_date" value="<?php if($postal_date !== ''){echo date('Y-m-d',strtotime($postal_date));} ?>"></td>
</tr>
<tr>
<td>Cards Loaded: </td>
<td><input type="checkbox" name="cards_loaded" value="1" <?php if($cards_loaded == 1){echo 'checked';} ?>></td>
<td>Tracking Number: </td>
<td><input type="text" name="tracking_number" size="30" value="<?php echo $tracking_number; ?>"></td>
</tr>
<tr>
<td colspan="4" style="text-align:center;">
Completed: <input type="checkbox" name="completed" value="1" <?php if($completed == 1){echo 'checked';} ?>>
<input type="submit" name="submit" value="Save" style="width:90px" />
</td>
</tr>
</table>
<script type="text/javascript">
var initialText = $('.editable').val();
$('.editOption').val(initialText);
$('#test').change(function(){
var selected = $('option:selected', this).attr('class');
var optionText = $('.editable').text();
if(selected == "editable"){
$('.editOption').show();
$('.editOption').keyup(function(){
var editText = $('.editOption').val();
$('.editable').val(editText);
$('.editable').html(editText);
});
}else{
$('.editOption').hide();
}
});
</script>
</body>
</html>
<?php
}
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit an existing record
if (isset($_GET['id'])) {
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit'])) {
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id'])) {
// get the form data
// I'll get to this later... get form to display first...
echo 'We are saving a new edit of job ' . $id;
}
// if the 'id' variable is not valid, show an error message
else {
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else {
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0) {
// get 'id' from URL
$id = $_GET['id'];
// get the record from database
if ($stmt = $connect->prepare("SELECT id, start_date, company, stock_code, card_quantity, fiske_print, carrier_quantity, quoted, quote_details, quoted_date, quote_accepted, quote_accepted_date, proof_sent, proof_sent_date,proof_approved, proof_approved_date, printed, print_date, closed_loop_allocated, invoiced, invoiced_date, posted, tracking_number, postal_date, paid, is_bulk_load, bulk_funds_received, cards_loaded, notes, completed FROM jobs WHERE id = ?")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($id,$start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s\n", $id,$start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
}
// show the form by executing renderForm()
renderForm(NULL, $id,$start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
// check to see if we have a quote date..?
echo 'quote date: '.$quote_date;
$stmt->close();
}
// show an error if the query has an error
else {
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else {
header("Location: addJob.php");
}
}
}
/*
NEW RECORD
*/
// if the 'id' variable is not set in the URL, we must be creating a new record
else {
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit'])) {
// get the form data
$start_date = date("Y-m-d", strtotime($_POST['start_date']));
$company = $_POST['company'];
$stock_code = $_POST['stock_code'];
$card_quantity = $_POST['card_quantity'];
$carrier_quantity = $_POST['carrier_quantity'];
$fiske_print = $_POST['fiske_print'];
$quoted = $_POST['quoted'];
$quote_details = $_POST['quote_details'];
$quote_date = date("Y-m-d", strtotime($_POST['quote_date']));
$quote_accepted = $_POST['quote_accepted'];
$quote_accepted_date = date("Y-m-d", strtotime($_POST['quote_accepted_date']));
$proof_sent = $_POST['proof_sent'];
$proof_sent_date = date("Y-m-d", strtotime($_POST['proof_sent_date']));
$proof_approved = $_POST['proof_approved'];
$proof_approved_date = date("Y-m-d", strtotime($_POST['proof_approved_date']));
$printed = $_POST['printed'];
$printed_date = date("Y-m-d", strtotime($_POST['printed_date']));
$closed_loop_allocated = $_POST['closed_loop_allocated'];
$invoiced = $_POST['invoiced'];
$invoice_date = date("Y-m-d", strtotime($_POST['invoice_date']));
$posted = $_POST['posted'];
$postal_date = date("Y-m-d", strtotime($_POST['postal_date']));
$tracking_number = $_POST['tracking_number'];
$paid = $_POST['paid'];
$is_bulk_load = $_POST['is_bulk_load'];
$bulk_funds_received = $_POST['bulk_funds_received'];
$cards_loaded = $_POST['cards_loaded'];
$completed = $_POST['completed'];
/* Prepare an insert statement */
$query = "INSERT INTO jobs (start_date,company,stock_code,card_quantity,fiske_print,carrier_quantity,quoted,quote_details,quoted_date,quote_accepted,quote_accepted_date,proof_sent,proof_sent_date,proof_approved,proof_approved_date,printed,print_date,closed_loop_allocated,invoiced,invoiced_date,posted,tracking_number,postal_date,paid,is_bulk_load,bulk_funds_received,cards_loaded,notes,completed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($connect, $query);
mysqli_stmt_bind_param($stmt, "sssssssssssssssssssssssssssss", $start_date,$company,$stock_code,$card_quantity,$fiske_print,$carrier_quantity,$quoted,$quote_details,$quote_date,$quote_accepted,$quote_accepted_date,$proof_sent,$proof_sent_date,$proof_approved,$proof_approved_date,$printed,$printed_date,$closed_loop_allocated,$invoiced,$invoice_date,$posted,$tracking_number,$postal_date,$paid,$is_bulk_load,$bulk_funds_received,$cards_loaded,$notes,$completed);
/* Execute the statement */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
// redirect the user
header("Location: index.php");
}
// if the form hasn't been submitted yet, show the form
else {
error_log('SQL error ('.__FILE__.' line '.__LINE__.'): '. $connect->error);
renderForm();
}
}
// close the mysqli connection
$connect->close();
?>

Form gets submitted if provide any value from form field Using PHP

When i provide value in any one field of form and click on ragister it gets submitted but should not submit till the all field get filled what i am doing wrong please let me know, as I have taken pre tag at the top where i can see all the values that i'm getting when i click on ragister.
<?php
$error_array = array();
$fname = $lname = $email = $dob = $Mchecked = $Fchecked = $hobbies ="";
if(isset($_GET["sbt_save"]))
{
echo '<pre>'; print_r($_GET); echo "</pre>";
if($_GET['fname']=="")
{
$err ="Please Enter your first name"."<br>";
array_push($error_array,$err);
}
else
{
$fname = test_input($_GET['fname']);
}
if($_GET['lname']=="")
{
$err ="Please Enter your last name"."<br>";
array_push($error_array,$err);
}
else
{
$lname = test_input($_GET["lname"]);
}
if($_GET['email']=="")
{
$err ="Please Enter your email"."<br>";
array_push($error_array,$err);
}
else
{
$email = test_input($_GET["email"]);
}
if($_GET['dob']=="")
{
$err ="Please Enter your date of birth"."<br>";
array_push($error_array,$err);
}
else
{
$dob = test_input($_GET["dob"]);
}
if(!isset($_GET["gender"]))
{
$err ="Please select gender"."<br>";
array_push($error_array,$err);
}
else
{
$gender = $_GET["gender"];
if ($gender == "Male")
{
$Mchecked = "checked";
}
else if ($gender == "Female")
{
$Fchecked = "checked";
}
}
if(!isset($_GET['hobbies']))
{
$err ="Please Enter your hobbies"."<br>";
array_push($error_array,$err);
}
else
{
$hobbies = test_input($_GET['hobbies']);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ragistration Form</title>
<link rel="stylesheet" type="text/css" href="ragistration_form.css">
<!--
<script src="jquery-2.2.1.min.js"></script>
<script>
$(document).ready(function(event)
{
$(".sbt_button").click(function(event)
{
var error_arr = [];
var email_value = $("#email").val();
var position_of_at = email_value.indexOf('#');
var position_of_dot = email_value.lastIndexOf('.');
if($("#fname").val() == null || $("#fname").val() == "")
{
var err = "First Name";
error_arr.push(err);
}
if($("#lname").val() == null || $("#lname").val() == "")
{
var err = "Last Name ";
error_arr.push(err);
}
if(position_of_at == -1 || position_of_dot == -1 || (position_of_at + 2) >= position_of_dot )
{
var err = "Email ";
error_arr.push(err);
}
if($("#dob").val() == null || $("#dob").val() == "")
{
var err = "Date of Birth ";
error_arr.push(err);
}
if(!$("input[type='radio']").is(":checked"))
{
var err = "Gender ";
error_arr.push(err);
}
if(!$("input[type='checkbox']").is(":checked"))
{
var err = "Hobbies ";
error_arr.push(err);
}
if(error_arr.length !=0)
{
event.preventDefault();
alert(error_arr);
}
});
});
</script>
-->
</head>
<body>
<form class="form" name="myForm" action="" method="GET">
<table>
<tr>
<p class="heading">Ragistration Form</p>
</tr>
<?php
if($error_array !="")
{
foreach($error_array as $value)
{
echo "<tr style='color:red;'><td> ". $value. "</td></tr>";
}
}
?>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td class="field_Name">First Name :<b style="color:red">*</b></td>
<td><input type="text" name="fname" id="fname" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Last Name :<b style="color:red">*</b></td>
<td><input type="text" name="lname" id="lname" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Email :<b style="color:red">*</b></td>
<td><input type="text" name="email" id="email" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Date of Birth :<b style="color:red">*</b></td>
<td><input type="date" name="dob" id="dob" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Gender :<b style="color:red">*</b></td>
<td><input type="radio" name="gender" value="Male"class="inputfield_Name" <?php echo $Mchecked;?> />
Male
<input type="radio" name="gender" value="Female" <?php echo $Fchecked;?> />
Female</td>
</tr>
<tr>
<td class="field_Name">About Yourself :</td>
<td><textarea name="abt" class="inputfield_Name"$></textarea></td>
</tr>
<tr>
<td class="field_Name">Hobbies :<b style="color:red">*</b></td>
<td><input name="hobbies" value="Cricket" type="checkbox" id="hobbies" class="inputfield_Name" />
Cricket
<input name="hobbies" value="Singing" type="checkbox" />
Singing
<input name="hobbies" value="Travling" type="checkbox" />
Travling</td>
<tr>
<td></td>
<td><input name="hobbies" value="Writing" type="checkbox" class="inputfield_Name" />
Writing
<input name="hobbies" value="Teaching" type="checkbox" />
Teaching
<input name="hobbies" value="Driving" type="checkbox" />
Driving </td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Ragister" name="sbt_save" class="sbt_button"/></td>
</td>
</tr>
</table>
</form>
</body>
</html>
I have tried your code, its working fine. See the below screenshot.
If you want to validate your form before submit then use the commented javascript/client-side validation and if you want to validate it afterwards then use your php/server-side validation.
Let me know if you are facing any other problem.

PHP $_POST Form validation and Postback

I am working on an assignment for my PHP1 Class and we are working on sticky forms, my assignment is to write an order form that validates that both a name is entered and a phone model is selected and if both are filled posts that data back to the page and if one or both is missing an error message is posted back to the page. Accessories are Optional. Currently the script will post an error if no phone is selected and a name is input into the form, it will post an error if both are missing, but if a name is missing and a phone is selected then it will not flag as an error and continue processing the script back to the page. I attempted to right a function to validate that both the userName text field AND a phones radio button are selected to be true or if false then the error message is presented. Can anyone tell me why my form is processing the data when only a phone model is selected and the name field is blank?
Script(OrderForm):
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
</head>
<body>
<h1>Order Your Smartphone</h1>
<?php
/**
* Created by PhpStorm.
* User: Daniel Vermillion
* Date: 10/27/2014
* Time: 7:59 PM
*/
$isValid = false;
//function totalAcc() {
// foreach($_POST['acc'] as $item) {
// $accPrice[] = $item;
// }
// array_sum($accPrice);
// return $accPrice;
//}
//function totalCost() {
// $subtotal = $phonePrice + $accPrice;
// $tax = 0.08;
// $taxTotal = $subtotal * $tax;
// $total = $subtotal + $taxTotal;
// return $subtotal;
// return $taxTotal;
// return $total;
//}
function validData() {
if(isset($_POST['userName']) && isset($_POST['phones'])) {
return true;
}
else {
return false;
}
}
function calcResults() {
$isValid = validData();
if($isValid) {
echo "Full Name: {$_POST['userName']} <br />";
echo "Phone Model: {$_POST['phones']} <br />";
echo "Accessories: {$_POST['acc']} <br />";
// echo "Subtotal: $subtotal <br />";
// echo "Tax: '$taxTotal' <br />";
// echo "Total Cost: $total <br />";
}
else {
echo "Please enter your name and select a phone model.";
}
}
?>
<form method="post" action="index.php">
Full Name: <input type="text" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>" /><br />
<h4>Add Smartphone</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Phone</td>
<td>Model</td>
<td>Storage</td>
<td>Price</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP8") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP8</td>
<td>8 GB</td>
<td>$400</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP16") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP16</td>
<td>16 GB</td>
<td>$450</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP8") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP8</td>
<td>8 GB</td>
<td>$500</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP16") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP16</td>
<td>16 GB</td>
<td>$550</td>
</tr>
</table>
<h4>Add Accessories</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Accessory</td>
<td>Price</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="handstrap" <?php if(isset($_POST['acc']) && in_array('handstrap', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Hand Strap</td>
<td>$6.25</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="leathercase" <?php if(isset($_POST['acc']) && in_array('leathercase', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Leather Case</td>
<td>$14.50</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="headphones" <?php if(isset($_POST['acc']) && in_array('headphones', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Headphones</td>
<td>$18.75</td>
</tr>
</table>
<br />
<input type="submit" name="submit" value="Click to Finalize Order" /><br /><br />
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
calcResults();
}
?>
</body>
</html>
isset() for strings returns true for an empty string.
https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
Try Empty()
edit: please note that if the field has a space in it, it will not be counted as empty. You should probably use Trim() on the result to ensure that there is no whitespace.
You need to echo the result..
replace
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
calcResults();
}
with
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo calcResults();
}
UPDATE:
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
</head>
<body>
<h1>Order Your Smartphone</h1>
<?php
/**
* Created by PhpStorm.
* User: Daniel Vermillion
* Date: 10/27/2014
* Time: 7:59 PM
*/
$isValid = false;
//function totalAcc() {
// foreach($_POST['acc'] as $item) {
// $accPrice[] = $item;
// }
// array_sum($accPrice);
// return $accPrice;
//}
//function totalCost() {
// $subtotal = $phonePrice + $accPrice;
// $tax = 0.08;
// $taxTotal = $subtotal * $tax;
// $total = $subtotal + $taxTotal;
// return $subtotal;
// return $taxTotal;
// return $total;
//}
function validData() {
if(isset($_POST['userName']) && !empty($_POST['userName'])) {
if(isset($_POST['phones']) && !empty($_POST['phones'])) {
$acc = (isset($_POST['acc']) && !empty($_POST['acc'])) ? " <br />Accessories: " . implode(" and ",$_POST['acc']) . " <br />" : "";
return "Full Name: " . $_POST['userName'] . " <br />Phone Model: " . $_POST['phones'] . $acc;
} else {
return "Please enter the phone model.";
}
} else {
return "Please enter your name and select a phone model.";
}
}
function calcResults() {
$isValid = validData();
return $isValid;
}
?>
<form method="post" action="form.php">
Full Name: <input type="text" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>" /><br />
<h4>Add Smartphone</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Phone</td>
<td>Model</td>
<td>Storage</td>
<td>Price</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP8") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP8</td>
<td>8 GB</td>
<td>$400</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP16") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP16</td>
<td>16 GB</td>
<td>$450</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP8") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP8</td>
<td>8 GB</td>
<td>$500</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP16") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP16</td>
<td>16 GB</td>
<td>$550</td>
</tr>
</table>
<h4>Add Accessories</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Accessory</td>
<td>Price</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="handstrap" <?php if(isset($_POST['acc']) && in_array('handstrap', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Hand Strap</td>
<td>$6.25</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="leathercase" <?php if(isset($_POST['acc']) && in_array('leathercase', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Leather Case</td>
<td>$14.50</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="headphones" <?php if(isset($_POST['acc']) && in_array('headphones', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Headphones</td>
<td>$18.75</td>
</tr>
</table>
<br />
<input type="submit" name="submit" value="Click to Finalize Order" /><br /><br />
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo calcResults();
}
?>
</body>
</html>

Undefined index:firstname,lastname,email,phone in line83

I am having problem in this following code.It says undefined index on line 83.The second problem is that there is a huge gap between the text fill the required form and the input textbox of the form during output.Please help me out.The code is posted below.
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$firstnameErr = $lastnameErr = $emailErr = "";
$firstname = $lastname = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["firstname"]))
{
$firstnameErr = "Name is required";
}
else
{
$firstname = test_input($_POST["firstname"]);
}
if (empty($_POST["lastname"]))
{
$lastnameErr = "Name is required";
}
else
{
$lastname = test_input($_POST["lastname"]);
}
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div text align =center><h1>Eventous Info</h1></div>
<h3>Fill the Required Form:</h3>
<p><span class="error">*required field</span></p>
<table>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<tr><?php// echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<td>Firstname:</td>
<td><input type="text" name="firstname" ></td>
<td><span class="error">* <?php echo $firstnameErr;?></span></td><br><br>
</tr>
<tr>
<td>Lastname:</td>
<td><input type="text" name="lastname" ></td>
<td><span class="error">* <?php echo $lastnameErr;?></span></td><br><br>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
<td><span class="error">* <?php echo $emailErr;?></span></td><br><br>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="number"><td><br><br>
</tr>
</table>
<input type="submit" >
</form>
<?php
$con = mysql_connect("localhost","ashu123","bangalore");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("evantus", $con);
$sql="INSERT INTO employee (firstname, lastname, email, phone )
***LINE-83***
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[email]','$_POST[number]')";
$sql = "select * from employee";
$query = mysql_query( $sql );
echo "<table>";
echo "<tr><th>firstname</th>";
echo "<th>lastname</th>";
echo "<th>email</th>";
echo "<th>phone</th></tr>";
while( $row = mysql_fetch_assoc($query) )
{
echo "<tr><td>$row[firstname]</td>";
echo "<td>$row[lastname]</td>";
echo "<td>$row[email]</td>";
echo "<td>$row[phone]</td></tr>";
}
echo "</table>";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con)
?>
</body>
</html>
Your form has invalid html code. In short, just use:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Firstname:</td>
<td><input type="text" name="firstname" ></td>
<td><span class="error">* <?php echo $firstnameErr;?></span><br /><br /></td>
</tr>
<tr>
<td>Lastname:</td>
<td><input type="text" name="lastname" ></td>
<td><span class="error">* <?php echo $lastnameErr;?></span><br /><br /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
<td><span class="error">* <?php echo $emailErr;?></span><br /><br /></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="number"><br /><br /><td>
<td></td>
</tr>
</table>
<input type="submit" >
</form>
More about it:
1. After opening the <table> element, next one must be table row, so <form> must be a wrapper to your table.
2. You have placed breaks after closing the </td> tag, which is wrong - they should be inside table cell.
3. Ref: undefined index, guess it is only a warning that you are using the $_POST variable that does not exist.
I feel your insert query is not right, try the query below.
$sql="INSERT INTO employee (firstname, lastname, email, phone ) VALUES ('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['email']."','".$_POST['number']."')";

How to keep input in fields after form submitted for further update

I wonder is it possible to keep the user input inside form field after form submitted, so that the user can update the entry. I've a html registration form [with some JS validation], then a php file to insert data to sql & meanwhile display back the inserted data in a table view. i also include the form's html code in php file so i can see the form after being submitted. but i couldn't keep the data in the field after form submitted! here is the 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">
<head>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="insert.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Submit" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
</body>
</html>
here is the insert.php file:
<!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">
<head>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="update.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Update" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
<br>
</div>
</form>
<div align="center">
<?php
if (!mysql_connect('localhost', 'root', '')) {
echo "Connected";
}
mysql_select_db("workshop");
// Get values from form
$ic = mysql_real_escape_string($_POST['ic']);
$name = mysql_real_escape_string($_POST['name']);
$contact = mysql_real_escape_string($_POST['contact']);
$mail = mysql_real_escape_string($_POST['mail']);
$address = mysql_real_escape_string($_POST['address']);
if (staff_detail_exist($ic) == "available") {
insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype);
echo "<p style='text-align:center; color:green;'>" . "Workshop application successful! You will be notified shortly via E-mail after confirmation! Thank You!";
} else if (staff_detail_exist($ic) == "exist") {
echo "<p style='text-align:center; color:red;'>" . "Record already exists! Please enter another Staff ID. Thank You!" . "</p>";
}
function insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype) {
$sql = "INSERT INTO apply (staffid, staffname, staffno, staffemail, staffaddress, paytype) VALUES ('$ic', '$name', '$contact', '$mail', '$address','$paytype')";
mysql_query($sql);
}
function staff_detail_exist($ic) {
$result = null;
$sql = "SELECT * FROM apply WHERE staffid = '$ic'";
$data = mysql_query($sql);
if (mysql_num_rows($data) == 0) {
$result = "available";
} else {
$result = "exist";
}
return $result;
}
$staffid = $_POST['ic'];
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("workshop", $con);
$result = mysql_query("SELECT * FROM apply where staffid = '$ic'");
echo "<table width=400 border=1 cellpadding=0 align=center>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<th>Staff/IC Number: </th><td>" . "<center>" . $row['staffid'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Name: </th><td>" . "<center>" . $row['staffname'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Email: </th><td>" . "<center>" . $row['staffemail'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Contact No.: </th><td>" . "<center>" . $row['staffno'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Address: </th><td>" . "<center>" . $row['staffaddress'] . "</center>" . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
I've tried to add like value="<? echo "$row['staffid']"?>" in the form's field at php file but no luck! I've only basic in php. So, any help? thank you!
thanks all, its finally working :) i've used value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" inside the input tag. so, its like: <input type="text" name="myField" value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" /> where myField is input name & myField_db is the column name from database.
Take the form posted values just above your html code like this
<?php
if (isset($_POST["submit"]) && $_POST["submit"]=='Submit') {
$name=$_POST["name"];
}
?>
And echo it in your html form.
<input name="name" type="text" id="name" size="45" value="<? echo $name?>"/>
I've used this function a few times; quite handy
function getPost($field){
return (isset($_POST[$field]) && $_POST[$field] != "" ? $_POST[$field] : "");
}
Usage
<input type="text" name="contact" value="<?php echo getPost("contact"); ?>" />
This is for the cases where a user submits information and is for some reason sent back to the form again - perhaps their entries didn't pass PHP validation, for example.

Categories