PHP $_POST Form validation and Postback - php

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>

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();
?>

i am trying to update my data with an image updation too but the image isset would not work in php

Hey guys i have created a register form with an image upload too but when i try to update this form i try to get the id but the isset of my image is not working so it just wont run my update query do check it out
this is the updation form where all the values will be displayed for edit now can i run the update function in the isset condition of my submit button and then update the data
<title>Register Update</title>
<?php
//error_reporting(0);
$id=$_GET['id'];
function __autoload($classname)
{
include "$classname.php";
}
$obj = new connect();
$st=$obj->con();
if (isset($_POST['sub']))
{
$upd= new update();
$upd->updatedata($_POST);
}
$qry = "select * from register ";
$run = mysqli_query($st,$qry);
$row = mysqli_fetch_assoc($run);
{
$g = $row['gen'];
$l = $row['lang'];
}
$query=mysqli_query($st,"select * from register where id='$id'");
//echo "<ul>";
while($query2=mysqli_fetch_assoc($query))
{
//print_r($query2);
echo "<form method='POST' action='RegisterRetrieve.php'>";
echo "<table>";
?>
<p><input type="hidden" name="sid" value="<?php echo $query2['id']; ?>"></p>
<tr>
<td>
First Name:
</td>
<td><input type="text" name="uname" value="<?php echo $query2['uname']; ?>"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd" value="<?php echo $query2['pwd']; ?>"></td>
</tr>
<tr>
<td>Email Id:</td>
<td><input type="text" name="emailid" value="<?php echo $query2['emailid']; ?>"
</td>
</tr>
<tr>
<td>Radio Button: Are you male or female?</td>
<?php
if ($g == "male"){
echo "<td><input type='radio' name='gen' value='Male' id='gen' checked> Male <input type='radio' name='gen' value='Female' id='gen'> Female </td>";
}
else
{
echo "<td><input type='radio' name='gen' value='Male' id='gen'> Male <input type='radio' name='gen' value='Female' id='gen' checked> Female </td>";
}
?>
</tr>
<tr>
<td>Check Box: Check the languages you know?</td>
<td><?php
$lang=explode(',',$l);
//print_r($lang);
if(in_array('Cricket', $lang))
echo '<input type="checkbox" name="lang[0]" value="Cricket" checked>Cricket';
else
echo '<input type="checkbox" name="lang[0]" value="Cricket">Cricket';
if(in_array('Basketball', $lang))
echo '<input type="checkbox" name="lang[1]" value="Basketball" checked>Basketball';
else
echo '<input type="checkbox" name="lang[1]" value="Basketball">Basketball';
if(in_array('Hockey', $lang))
echo '<input type="checkbox" name="lang[2]" value="Hockey" checked>Hockey';
else
echo '<input type="checkbox" name="lang[2]" value="Hockey">Hockey'."<br>";
?>
</td>
</tr>
<tr>
<td>Mobile No:</td>
<td><input type="text" name="mobile" value="<?php echo $query2['mobile']; ?>"
</td>
</tr>
<tr>
<td>10th Marks:</td>
<td><input type="text" name="marks_10" value="<?php echo $query2['10marks'];?>"
</td>
</tr>
<tr>
<td>
12th Marks:</td>
<td><input type="text" name="marks_12" value="<?php echo $query2['12marks'];?>"</td>
</tr>
<tr>
<td>
Browse Image:</td>
<td><input type="file" name="file1"></td>
<td><img src='img/<?php echo $query2['name'];?>' width='150px' height='150px'></td>
</tr>
<tr>
<td>
<select name="priority">
<option value="admin">
admin
</option>
<option value="<?php echo $query2['priority']; ?>"><?php echo $query2['priority']; ?>
</option>
<option value="superadmin">
superadmin
</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="submit" name="sub"><br>
</td>
</tr>
<?php
echo "<table>";
echo "</form>";
}
//echo "</ul>";
?>
now my update query which i m using but when i try to isset my image it just wont go in that condition
<?php
class update extends connect
{
function updatedata($rel)
{
$obj= new connect();
$obj->con();
extract($_POST);
$id=$_GET['id'];
$line = implode("," ,$lang);
print_r($_POST);
if(isset($_FILES["file1"]))
{
extract($_POST);
echo "hello";
$name = $_FILES['file1']['name'];
$type = $_FILES['file1']['type'];
$size = $_FILES['file1']['size'];
$tmp_name = $_FILES['file1']['tmp_name'];
$loc = 'img/';
$ext = substr($name,strpos($name,'.')+1);
if($_FILES['file1']['size']>= '10000' || $_FILES['file1']['size']<="23000000")
{
//echo $size;
}
else{
// echo "size is not supported";
}
$val = $_FILES['file1']['size'];
if($ext == 'jpg' || $ext == 'png')
{
//echo $lang;
//print_r($_POST);
//exit;
$val =("update register set uname='$uname',pwd='$pwd',emailid='$emailid',gen='$gen',lang='$line',mobile='$mobile',10marks='$marks_10',12marks='$marks_12' file1='$name' where id=$sid");
//print_r($qry);
$res=mysqli_query($this->con(),$val);
//print_r($run);
if($res)
{
move_uploaded_file($tmp_name,$loc.$name);
//echo "data saved";
//echo "Data inserted";
}
else
{
//echo "Data Not Inserted";
}
}
}
}
//print_r($val);
// return $res;
}
?>
Your html is broken:
</tr>
<?php
echo "<table>"; <--shouldn't this be </table>?
echo "</form>";
}

Issue in hobbies, as unable to get selected values using 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>

Uploading files to Google Drive

I am trying to upload files from my PHP-based website to Google Drive. I searched, got google-api-php-client library. In documentation an example is given but that can be run on php shell (Command line). I tried to run that example in browser, I got error of curl extention, and fixed that.
Now I am getting error related to authenticating code to allow access. I do not need authentication at all in my project, but for the time being I can try with it.
I have the following code in www.mydomain.com/drive/index.php file:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('MY-CLIENT-ID');
$client->setClientSecret('MY-CLIENT-SECRET');
$client->setRedirectUri('http://www.MY-DOMAIN.com/drive/auth.php');
//AUTH.PHP should have code to authenticate code and return back another code.
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
//**********************authentication process for SHELL
//I want this authentication process to remove at all or convert to web based authentication
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//************************************************************
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
Can I upload file without authentication need for each upload? If yes then how? If no then how to authenticate?
You can't use the exact same example that is meant for console development into web development.
You should do some changes, I'll give you mine as an example :
<?php
require_once 'googleapi/Google_Client.php';
require_once 'googleapi/contrib/Google_DriveService.php';
session_start();
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setApplicationName('Google+ PHP Starter Application');
$client->setClientId('ID');
$client->setClientSecret('Secret');
$client->setRedirectUri('Redirect');
//Voy a la dirección de la creación del permiso
$authUrl = $client->createAuthUrl();
print "<a href='$authUrl'>Connect Me!</a>";
//Regreso de la dirección con el código con el que puedo autenticarme
if (isset($_GET['code'])) {
$accessToken = $client->authenticate($_GET['code']);
file_put_contents('conf.json', $accessToken);
$client->setAccessToken($accessToken);
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
$client->setAccessToken(file_get_contents('conf.json'));
if ($client->getAccessToken()) {
//Significa que tengo derecho a manipular el servicio como quiera
// Elijo el servicio que quiero usar
$service = new Google_DriveService($client);
$file = new Google_DriveFile();
/*$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
print "test";*/
}
?>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$address=$_POST['address'];
$country=$_POST['country'];
$gender=$_POST['gender'];
$hobby = implode(',', $_POST['hobby']);
echo $ins="insert into itech (`name`,`email`,`address`,`country`,`gender`,`hobby`)values('".$name."','".$email."','".$address."','".$country."','".$gender."','".$hobby."')";
mysql_query($ins);
//header('location:view.php');
}
?>
<html>
<head></head>
<body>
<form name="add.php" method="post" onSubmit="return validate()">
<table align="center" border="1">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea rows="5" cols="20" name="address" wrap="physical"</textarea>
</textarea>
</td>
</tr>
<tr>
<td>
Country:<br/></td>
<td>
<select name="country" id="country">
<option value="">Select Country</option>
<option value="India">India</option>
<option value="U.S.A">U.S.A</option>
<option value="Canada">Canada</option></select>:<br />
</td>
</tr>
<tr>
<td>Gender</td>
<td>
Male:<input type="radio" value="Male" name="gender">:<br />
Female:<input type="radio" value="Female" name="gender">:<br />
</td>
</tr>
<tr>
<td>Hobbies</td>
<td>
<input type="checkbox" name="hobby[]" value="cricket">cricket<br/>
<input type="checkbox" name="hobby[]" value="Music">Music<br/>
<input type="checkbox" name="hobby[]" value="Movie">Movie<br/>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
function validate()
{
if(document.getElementById("name").value=="")
{
alert("Please Enter Your Name");
document.getElementById("name").focus();
return false;
}
if(document.getElementById("email").value=="")
{
alert("Please Enter Your Email Id");
document.getElementById("email").focus();
return false;
}
if(document.getElementById("address").value=="")
{
alert("Please Enter Your Address ");
document.getElementById("address").focus();
return false;
}
return true;
}
</script>
*****************************************************************************
edit.php
**************************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
$id=$_GET['id'];
$qry="select * from itech where id=$id";
$data=mysql_query($qry);
$result=mysql_fetch_assoc($data);
echo $result['hobby'];
//echo $id;
if(isset($_POST['update']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$address=$_POST['address'];
$gender=$_POST['gender'];
$hobby = implode(',', $_POST['hobby']);
echo $upd="update itech SET name='$name',email='$email',address='$address',gender='$gender',hobby='$hobby' where id=$id";exit;
mysql_query($upd);
header('location:view.php');
}
?>
<html>
<head></head>
<body>
<form name="edit.php" method="post">
<table align="center" border="1">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name" value="<?php echo $result['name'];?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email" value="<?php echo $result['name'];?>"></td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea rows="5" cols="20" name="address" id="address" >
<?php echo $result['address'];?>
</textarea>
</td>
</tr>
<tr>
<td>
Country:<br/></td>
<td>
<select name="country">
<option value="">Select Country</option>
<option value="<?php echo $result["id"]; ?>"
<?//php if($result["id"]==$_REQUEST["cat_id"]) { echo "Selected"; } ?>>
<?//php echo $r["category_name"]; ?></option>
<option value="India" <?php if($result['country']=='India') { echo "Selected"; }?>>India</option>
<option value="U.S.A" <?php if($result['country']=='U.S.A') { echo "Selected"; }?>>U.S.A</option>
<option value="Canada"<?php if($result['country']=='Canada') { echo "Selected"; }?>>Canada</option></select>:<br />
</td>
</tr>
<tr>
<td>Gender</td>
<td>
<?php
if($result['gender']=='Male')
{ ?>
Male:<input type="radio" value="Male" name="gender" CHECKED><br />
Female:<input type="radio" value="Female" name="gender"><br />
<?php }elseif ($result['gender'] == 'Female') {?>
Male:<input type="radio" value="Male" name="gender" ><br />
Female:<input type="radio" value="Female" name="gender" CHECKED><br />
<?php }?>
</td>
</tr>
<tr>
<td>Hobbies</td>
<td>
<input type="checkbox" name="hobby[]" value="cricket" <?php if($result['hobby']=='cricket') { echo "checked=checked"; }?>>cricket<br/>
<input type="checkbox" name="hobby[]" value="Music" <?php if($result['hobby']=='Music') {echo "checked=checked";}?>>Music<br/>
<input type="checkbox" name="hobby[]" value="Movie" <?php if($result['hobby']=='Movie') { echo "checked=checked";}?>>Movie<br/>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="update" value="update"></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
function validation()
{
if(document.getElementById(name).value="");
{
alert("Plz Enter Your Name");
document.getElementById(name).focus();
return false;
}
if(document.getElementById(email).value="");
{
alert("Plz enter Emailid");
document.getElementById(emailid).focus();
return false;
}
if(document.getElementById(address).value="");
{
alert("Plz Enter Your Address");
document.getElementById(address).focus();
return false;
}
if(document.getElementById(gender).value="");
{
alert("Plz Select your gender");
document.getElementById(gender).focus();
return false;
}
if(document.getElementById(hobby).value="");
{
alert("Plz Select your Hobby");
document.getElementById(hobby).focus();
return false;
}
return true;
}
</script>
**********************************************
view.php
******************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
?>
<html>
<head></head>
<body>
<table align="center" border="1">
<tr>
<th>Name</th>
<th>EmailId</th>
<th>Address</th>
<th>Country</th>
<th>Gender</th>
<th>Hobby</th>
<th>Action</th>
</tr>
<?php
$sel="select * from itech";
$data=mysql_query($sel);
while($result=mysql_fetch_assoc($data))
{?>
<tr>
<td><?php echo $result['name'];?></td>
<td><?php echo $result['email'];?></td>
<td><?php echo $result['address'];?></td>
<td><?php echo $result['country'];?></td>
<td><?php echo $result['gender'];?></td>
<td><?php echo $result['hobby'];?></td>
<td>Edit
Delete
</td>
</tr>
<?php
}?>
</table>
</body>
</html>
**********************************************
pagination.php
******************************************
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW-PAGINATED.PHP
Displays all data from 'players' table
This is a modified version of view.php that includes pagination
*/
// connect to the database
include('connect-db.php');
// number of results to show per page
$per_page = 3;
// figure out the total pages in the database
$result = mysql_query("SELECT * FROM players");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view-paginated.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($result, $i, 'id') . '</td>';
echo '<td>' . mysql_result($result, $i, 'firstname') . '</td>';
echo '<td>' . mysql_result($result, $i, 'lastname') . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
?>
<p>Add a new record</p>
</body>
</html>
login.php
***************************************
<?php
session_start();
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
if(isset($_POST['submit']))
{
$email=$_REQUEST['email'];
$pass=$_REQUEST['password'];
$sel="select * from elite where email='$email' and password='$pass'";
$res= mysql_query($sel);
$co= mysql_num_rows($res);
echo $co;
header("location:view.php");
if($co>0)
{
$row=mysql_fetch_array($res);
$_SESSION['email']=$row['email'];
header("location:view.php");
}
else
{
echo "Please enter correct username or password....";
header("location:login.php");
}
}
?>
<html>
<head>
</head>
<body>
<fieldset style="background-color: lightblue;height: 400px;width: 500px;margin-left: 400px;margin-top: 120px;">
<form action="" method="post">
<h1 align="center" style="color: red;">Login Page</h1>
<table align="center" border="1">
<tr>
<td><b>Email</b></td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td><b>PassWord</b></td>
<td><input type="password" name="password"></td>
</tr>
</table><br /><br />
<b><input type="submit" name="submit" value="submit" style="margin-left: 220px;color: red;"></b>
</form>
</fieldset>
</body>
</html>
*********************************************************
logout.php
**********************************************************
<?php
session_start();
session_destroy();
header("Location: login.php");
exit;
?>
******************************
add.php
**********************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
if(isset($_POST['submit']))
{
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$password=$_POST['password'];
move_uploaded_file($_FILES['image']['tmp_name'] ,"upload/".$_FILES['image']['name']);
$img = $_FILES['image']['name'];
$dob=$_POST['dob'];
$address=$_POST['address'];
echo $ins="insert into elite (`firstname`,`lastname`,`email`,`password`,`image`,`dob`,`address`)
values('".$firstname."','".$lastname."','".$email."','".$password."','".$img."','".$dob."','".$address."')";
mysql_query($ins);
header('location:view.php');
}
?>
<html>
<head>
</head>
<body>
<table align="center" border="1">
<form name="add.php" method="post" enctype="multipart/form-data" onsubmit="return validation()">
<tr>
<td>FirstName</td>
<td><input type="text" id="firstname" name="firstname"></td>
</tr>
<tr>
<td>LastName</td>
<td><input type="text" id="lastname" name="lastname"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="password" name="password"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" id="image" name="image"> </td>
</tr>
<tr>
<td>Dob</td>
<td> <input type="text" name='dob' id="datepicker" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" id="address" name="address"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" id="submit"></td>
</tr>
</form>
</table>
</body>
</html>
<script type="text/javascript">
function validation()
{
if(document.getElementById("firstname").value=="")
{
alert("Please Enter FirstName");
document.getElementById("firstname").focus();
return false;
}
if(document.getElementById("lastname").value=="")
{
alert("Please Enter lastname");
document.getElementById("lastname").focus();
return false;
}
var email = document.getElementById('email');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value))
{
alert('Please provide a valid email address');
email.focus;
return false;
}
if(document.getElementById("password").value=="")
{
alert("Please Enter password");
document.getElementById("password").focus();
return false;
}
if(document.getElementById("image").value=="")
{
alert("Please upload image");
document.getElementById("image").focus();
return false;
}
if(document.getElementById("dob").value=="")
{
alert("Please enter date");
document.getElementById("dob").focus();
return false;
}
if(document.getElementById("address").value=="")
{
alert("Please Enter address");
document.getElementById("address").focus();
return false;
}
return true;
}
</script>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
</body>
</html>
***************************************
view.php
************************************
<?php
session_start();
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
echo $_SESSION['email'];
if(!isset($_SESSION['email']))
{
header("location:login.php");
}
?>
<html>
<head></head>
<body></body>
<table align="center" border="1">
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Email</th>
<th>Password</th>
<th>Image</th>
<th>D.O.B</th>
<th>Address</th>
<th>Action</th>
</tr>
<?php
$vs="select * from elite";
$data=mysql_query($vs);
while($result=mysql_fetch_assoc($data))
{?>
<tr>
<td><?php echo $result['firstname'];?></td>
<td><?php echo $result['lastname'];?></td>
<td><?php echo $result['email'];?></td>
<td><?php echo $result['password'];?></td>
<td><img src="<?php echo "upload/".$result['image']; ?>" alt="" width="50px" height="50px"></td>
<td><?php echo $result['dob'];?></td>
<td><?php echo $result['address'];?></td>
<td><a href="edit.php? id=<?php echo $result['id'];?>">Edit</td>
<td><a href="delete.php? id=<?php echo $result['id'];?>">Delete</td>
<td><a href="logout.php?">Logout</td>
</tr>
<?php
}
?>
</table>
</html>
********************************************************
edit.php
*********************************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
$id=$_GET['id'];
echo $sel="select * from elite where id=$id";
$data=mysql_query($sel);
$res=mysql_fetch_assoc($data);
if(isset($_POST['update']))
{
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$password=$_POST['password'];
move_uploaded_file($_FILES['image']['tmp_name'] ,"upload/".$_FILES['image']['name']);
$img = $_FILES['image']['name'];
$dob=$_POST['dob'];
$address=$_POST['address'];
$upd="update elite SET firstname='$firstname',lastname='$lastname',email='$email',password='$password',image='$img',dob='$dob',address='$address' where id=$id";
mysql_query($upd);
header('location:view.php');
}
?>
<html>
<head>
</head>
<body>
<table align="center" border="1">
<form name="edit.php" method="post" enctype="multipart/form-data" onsubmit="return validation()">
<tr>
<td>FirstName</td>
<td><input type="text" id="firstname" name="firstname" value="<?php echo $res['firstname'];?>"></td>
</tr>
<tr>
<td>LastName</td>
<td><input type="text" id="lastname" name="lastname"value="<?php echo $res['lastname'];?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email"value="<?php echo $res['email'];?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="password" name="password"value="<?php echo $res['password'];?>"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" id="image" name="image"value="<?php echo $res['image'];?>"> </td>
</tr>
<tr>
<td>Dob</td>
<td><input type="text" id="datepicker" name="dob"value="<?php echo $res['dob'];?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" id="address" name="address"value="<?php echo $res['address'];?>"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="update" value="update"></td>
</tr>
</form>
</table>
</body>
</html>
<script type="text/javascript">
function validation()
{
if(document.getElementById("firstname").value=="")
{
alert("Please Enter FirstName");
document.getElementById("firstname").focus();
return false;
}
if(document.getElementById("lastname").value=="")
{
alert("Please Enter lastname");
document.getElementById("lastname").focus();
return false;
}
if(document.getElementById("email").value=="")
{
alert("Please Enter emailid");
document.getElementById("email").focus();
return false;
}
if(document.getElementById("password").value=="")
{
alert("Please Enter password");
document.getElementById("password").focus();
return false;
}
if(document.getElementById("image").value=="")
{
alert("Please upload image");
document.getElementById("image").focus();
return false;
}
if(document.getElementById("dob").value=="")
{
alert("Please enter date");
document.getElementById("dob").focus();
return false;
}
if(document.getElementById("address").value=="")
{
alert("Please Enter address");
document.getElementById("address").focus();
return false;
}
return true;
}
</script>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
****************************************************
delete.php
*************************************************
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("trainee_devang",$con);
$id=$_GET['id'];
$del="delete from elite where id=$id";
mysql_query($del);
header('location:view.php');
?>

Pass back values to form to populate it? (lots of values)

I need to pass back a large string of results to a form, so that the form can read those results from the URL and then populate the form with them. Problem is, the link ends up being:
&key=value&key=value ... until it can't process anymore (I assume a URL has a length limit?) resulting in my form not being able to fully populate. I need another way to pass values back to my form file.
VIEW.php file (basically just a table of values right as they are from the database, with the first column "id" being a link. When I click on "id", it goes back to my add.php(form page) and populates the form with the data matching that id)
<table border="0" cellpadding="0" cellspacing="0" id="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>MANUFACTURER</th>
<th>MODEL</th>
<th>DESCRIPTION</th>
<th>ON HAND</th>
<th>REORDER</th>
<th>COST</th>
<th>PRICE</th>
<th>SALE</th>
<th>DISCOUNT</th>
<th>DELETED</th>
<th></th>
</tr>
</thead>
<tbody>
<?php } ?>
<?php
// loop to fetch data
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='molszewski1_a2_add.php'>$row[id]</a></td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td>$row[deleted]</td>";
$status = "$row[deleted]";
echo "<td><a href='molszewski1_a2_delete.php?id=$row[id]&flag=$status&sort=$sort'>";
$status = "$row[deleted]";
if ($status == 'n') {
$flag = "restore";
echo "delete";
} else if ( $status == 'y') {
$flag = "delete";
echo "restore";
}
echo "</a></td>";
echo "</tr>";
} ?>
<?php { ?>
</tbody>
</table>
ADD.php (form page where the form is supposed to fetch the data and populate it)
<?php
// If no form has been submitted, present form
if (empty($_GET))
{
add_form();
}
// if a form has been submitted
else
{
// if form_validity() == 1, proceed to connect
if (form_validity() == 1)
{
// connect to mysql + database
connect();
$saleItem = "n";
$discountItem = "n";
if( array_key_exists( 'saleItem', $_GET ) && $_GET['saleItem'] == 'y' )
{ $saleItem = "y"; }
if( array_key_exists( 'discountItem', $_GET ) && $_GET['discountItem'] == 'y' )
{ $discountItem = "y"; }
// get values from form, insert into database
$sql=("INSERT INTO inventory (name,
manufac,
model,
descrip,
onhand,
reorder,
cost,
price,
sale,
discont,
deleted)
VALUES ('$_GET[itemName]',
'$_GET[manufacturer]',
'$_GET[model]',
'$_GET[description]',
'$_GET[numberOnHand]',
'$_GET[reorderLevel]',
'$_GET[cost]',
'$_GET[sellingPrice]',
'$saleItem',
'$discountItem', 'n')");
// if the query doesn't work, display error message
if (!(mysql_query($sql))) { die ("could not query: " . mysql_error()); }
add_form();
// redirect to view.php after form submission
// use php instead
echo "<meta http-equiv='REFRESH' content='0;url=molszewski1_a2_view.php'>";
}
else
{
// if form is not valid (form_validity returns 0), display error messages
add_form();
}
}
?>
FUNCTIONS.php (all my functions for stuff like the form)
<?php function page_navigation(){ ?>
<div class="center">
<input type="button" value="ADD" />
<input type="button" value="VIEW" />
<input type="button" value="VIEW DELETED" />
<input type="button" value="VIEW ACTIVE" />
<br />
<br />
</div>
<?php } ?>
<?php function add_form() { ?>
<form action="molszewski1_a2_add.php" method="get" id="form">
<table width="529px">
<tr>
<td>ITEM NAME</td>
<td><input name="itemName" size="30" type="text" value="<?php echo $_GET["itemName"] ?>"/></td>
</tr>
<tr>
<td>MANUFACTURER</td>
<td><input name="manufacturer" size="30" type="text" value="<?php echo $_GET["manufacturer"] ?>"/></td>
</tr>
<tr>
<td>MODEL</td>
<td><input name="model" size="30" type="text" value="<?php echo $_GET["model"] ?>"/></td>
</tr>
<tr>
<td>DESCRIPTION</td>
<td><textarea name="description" rows="3" cols="20"><?php echo $_GET["description"] ?></textarea></td>
</tr>
<tr>
<td>ON HAND</td>
<td><input name="numberOnHand" size="30" type="text" value="<?php echo $_GET["numberOnHand"] ?>"/></td>
</tr>
<tr>
<td>REORDER LEVEL</td>
<td><input name="reorderLevel" size="30" type="text" value="<?php echo $_GET["reorderLevel"] ?>"/></td>
</tr>
<tr>
<td>COST</td>
<td><input name="cost" size="30" type="text" value="<?php echo $_GET["cost"] ?>"/></td>
</tr>
<tr>
<td>SELLING PRICE</td>
<td><input name="sellingPrice" size="30" type="text" value="<?php echo $_GET["sellingPrice"] ?>"/></td>
</tr>
<tr>
<td>SALE ITEM</td>
<td>
<input type="checkbox" name="saleItem" value="y" <?php if( isset( $_GET['saleItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td>DISCOUNTED ITEM</td>
<td>
<input type="checkbox" name="discountItem" value="y" <?php if( isset( $_GET['discountItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="save" name="submit" id="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Use method="post" and $_POST (instead of $_GET).
POST requests can be much larger than GET requests as GET requests are limited by the maximum length of a URL. POST requests are limited by the size of the max_post_size ini-value which is usually a few megabytes.

Categories