I decided to create my first Wordpress plugin, then I switched to create a template instead, because I had problems with sending the data through form action. Now I have problems with adding data to databse using a template. I have a problem with my functions.php file I think. Can someone help me, please? The code:
<?php
if(isset($_POST['submitbtn']))
{
global $wpdb;
$data_array = array(
'OrderNum' => $_POST['OrderNum'],
'OrderStatus' => $_POST['OrderStatus'],
'ClientFirstName' => $_POST['ClientFirstName'],
'ClientLastName' => $_POST['ClientLastName']
);
$table_name = 'ordernumber';
$sql=$wpdb->insert($table_name, $data_array, $format=NULL);
if($sql == 1){
echo '<h1>Added</h1>';
}else{
echo 'Error';
}
}
?>
EDIT:
For some reason I can't add my whole second php file here so here is just the form, and I want to add I am a beginner in this all. `
<form method = "post">
<fieldset>
<p><label for="ClientFirstName">First name:</label>
<input type="text" id="ClientFirstName" name="ClientFirstName"/>
</p>
<p><label for="ClientLastName">Last name:</label>
<input type="text" id="ClientLastName" name="ClientLastName"/>
</p>
<p><label for="OrderNum">Order number: </label>
<input type="text" id="OrderNum" name="OrderNum"/>
</p>
<p><label for="OrderStatus">Order status: </label>
<select name="OrderStatus" id="OrderStatus">
<option value="Your order is wating for">Your order is wating</option>
<option value="Order is shipped">Order is shipped.</option>
<option value="Done">Done</option>
<option value="Error in order">Error in order </option>
</select>
</p>
</fieldset>
<p><input type="submit" value="Add order" name="submitbtn"></p>
</form>`
Related
I made a page in php to get some data from mysql server using jquery post. The post method returns a json object. The json object contains a key named 'warning' if the record requested is already processed one. Else it contains several key value pairs from the requested record. But I am unable to check whether the json object contains a key called 'warning'. What is the problem with my code?
Given below is the form.
<form id="transitentry" name="transitentry" >
<fieldset>
<legend>Voucher Details</legend>
<label for "insert_id">Enter ID:</label><input type="text" id="insert_id" required/><br/>
<label for "voucher_type">Type of Voucher</label>
<select name="voucher_type" id="voucher_type" required>
<option class="green" value="">----Select Voucher Type----</option>
<option class="green" value="Invoice">Invoice</option>
<option class="green" value="Hand Receipt">Hand Receipt</option>
<option class="green" value="Manuscript Voucher">Manuscript Voucher</option>
</select>
<br/><br/>
<label for "invoice_no">Invoice No.:</label><input type="text" id="invoice_no"/><br/>
<label for "invoice_dt">Invoice/Receipt Date:</label><input type="text" id="datepicker" name="datepicker" value="<?php echo $dateindian; //echo date('d-m-Y'); ?>" /><input type="hidden" id="stddate" value="<?php echo $dateus; //echo date('d-m-Y'); ?>"/><br/>
<label for "item">Item/Description:</label><input class="item" type="text" id="item" size="100" required/><br/>
<label for "uom">Unit:</label><input type="text" id="uom" required/><br/>
<label for "qty">Qty:</label><input type="text" id="qty" required/><br/>
<label for "amount">Amount:</label><input type="text" id="amount" required/><br/>
<label for "supplier">Supplier</label><input type="text" id="supplier" required/><br/>
<label for "gst">GST :</label><input class="checkmark" type="checkbox" id="gst" value="Y"/><br/><br/>
<div align="center"><input id="frmsubmit" type="submit" value="Submit" /></div>
</fieldset>
</form>
Following jquery code is placed in the page to handle post
jQuery('#insert_id').change(function(){
var id=jQuery(this).val();
jQuery.post("scripts/get_imprest_transaction.php",{"insert_id":id},function(data){
if(data.hasKey("warning")){
alert(data.warning);
}else{
jQuery("#voucher_type").val(data.voucher_type);
jQuery("#invoice_no").val(data.bill_no);
jQuery("#datepicker").val(data.dateindian);
jQuery("#stddate").val(data.date);
jQuery("#item").val(data.iitem);
jQuery("#uom").val(data.uom);
jQuery("#qty").val(data.qty);
jQuery("#amount").val(data.amount);
jQuery("#supplier").val(data.supplier);
}
});
get_imprest_transaction.php which sends json object
require_once('../Connections/hari.php');
$insert_id=$_POST['insert_id'];
mysql_select_db($database_hari,$hari);
$sql= "SELECT * from imprest where transact_id=$insert_id";
$result=mysql_query($sql) or die(mysql_error());
$row=mysql_fetch_array($result);
if (mysql_num_rows($result)==0){
$return_data=array('msg'=>'Invalid ID or Data Not Entered');
header('Content-Type: application/json');
echo json_encode($return_data);
exit();
}else {
//$row=mysql_fetch_array($result);
if(is_null($row['submission_dt'])){
$warning='This transaction is already submitted for claim. If you change data , record in the database will differ from the hardcopy submitted to F&A';
$return_data=array( 'warning'=>$warning);
}else{
$dateindian= date('d-m-Y',strtotime($row['bill_dt']));
$item=$row['item'];
$date=$row['bill_dt'];
$uom=$row['uom'];
$qty=$row['qty'];
$amount=$row['amount'];
$bill_no=$row['bill_no'];
$gst=$row['gst'];
$voucher_type=$row['voucher_type'];
$supplier=$row['supplier'];
$return_data=array('iitem'=>$row['item'],'date'=>$row['bill_dt'], 'uom'=>$row['uom'], 'qty'=>$row['qty'], 'amount'=>$row['amount'], 'bill_no'=>$row['bill_no'], 'dateindian'=>$dateindian, 'gst'=>$row['gst'], 'voucher_type'=>$row['voucher_type'], 'supplier'=>$row['supplier']); }
header('Content-Type: application/json');
echo json_encode($return_data);
exit();
}
data is an object that represents the parsed JSON, returned by jQuery's post.
The problem is that there's no hasKey function that's defined as part of this object, so you can't call data.hasKey.
Now, assuming warning is a first-level property (and not a nested one), you can simply replace:
if (data.hasKey('warning'))
with:
if (data.warning !== undefined)
I have a form in a php page that I want to have updated as the drop down is changed. Here is the code for the form:
<form action="AdminPage.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="action" value="version" />
<label><strong>Name:</strong></label>
<select id="WebName" name="Name">
<option value="ReportDashboard">ReportDashboard</option>
<option value="ReportDashboard Dev"<?php if(strpos($_SERVER['PHP_SELF'],"dev/FrontierReports",1) > 0){echo " selected='selected'";}?>>ReportDashboard Dev</option>
<option value="ReportDashboard Testing"<?php if(strpos($_SERVER['PHP_SELF'],"dev/Testing",1) > 0){echo " selected='selected'";}?>>ReportDashboard Testing</option>
</select><p></p>
<label><strong>Version Number: </strong></label>
<input id="VersionNumber" type="text" name="VersionNumber" value="<?php echo $VersionNumber['VersionNo']; ?>" /><p></p>
<label><strong>Version Type:</strong></label>
<select id="Type" name="VersionType">
<option value="1">Major</option>
<option value="2">Minor</option>
<option value="3" selected="selected">Bug</option>
</select><p></p>
<input type="hidden" name="VersionNumberCheck" value="<?php echo $VersionNumber['VersionNo']; ?>" />
<label><strong>Notes</strong></label>
<input id="Notes" type="text" name="Notes" value="<?php echo $ReleaseNotes['ReleaseNotes']; ?>" />
<p><input class="Pointer" type="submit" name="submit" value="Update Version" /></p>
<p><input id="VersionSubmit" class="Pointer" type="button" name="VersionSubmit" value="Current Notes" /></p>
</form>
Currently, the form gets its values for the 2 text fields (VersionNumber and Notes) from outside the form. I would like to have them be obtained as the form is created based on what the first drop down (Name) has selected and then update if that drop down gets changed.
I thought of adding some PHP to the form to help, but it doesn't work. Here is what I tried:
<form action="AdminPage.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="action" value="version" />
<label><strong>Name:</strong></label>
<select id="WebName" name="Name">
<option value="ReportDashboard">ReportDashboard</option>
<option value="ReportDashboard Dev"<?php if(strpos($_SERVER['PHP_SELF'],"dev/FrontierReports",1) > 0){echo " selected='selected'";}?>>ReportDashboard Dev</option>
<option value="ReportDashboard Testing"<?php if(strpos($_SERVER['PHP_SELF'],"dev/Testing",1) > 0){echo " selected='selected'";}?>>ReportDashboard Testing</option>
</select><p></p>
<?php
$Vsql = "select top 1 VersionNo,ReleaseNotes from pmdb.Version where Name = 'ReportDashboard' order by name,VersionNo desc";
$GetVersion = $conn->query($Vsql);
$VersionNumber = $GetVersion->fetch(PDO::FETCH_ASSOC);
?>
<label><strong>Version Number: </strong></label>
<input id="VersionNumber" type="text" name="VersionNumber" value="<?php echo $VersionNumber['VersionNo']; ?>" /><p></p>
<label><strong>Version Type:</strong></label>
<select id="Type" name="VersionType">
<option value="1">Major</option>
<option value="2">Minor</option>
<option value="3" selected="selected">Bug</option>
</select><p></p>
<input type="hidden" name="VersionNumberCheck" value="<?php echo $VersionNumber['VersionNo']; ?>" />
<label><strong>Notes</strong></label>
<input id="Notes" type="text" name="Notes" value="<?php echo $ReleaseNotes['ReleaseNotes']; ?>" />
<p><input class="Pointer" type="submit" name="submit" value="Update Version" /></p>
<p><input id="VersionSubmit" class="Pointer" type="button" name="VersionSubmit" value="Current Notes" /></p>
</form>
I don't know how to capture what is in the drop down to change the SQL that is pulling the data. I thought of possibly just pulling all of the rows back and then doing a search against it once the form is built, but I still don't know how to capture when the drop down changes and then update the 2 text boxes.
UPDATE
I now have a new file named UpdateAdminVersion.php this is what is has:
$Vsql = "select top 1 VersionNo,ReleaseNotes from pmdb.Version where Name = 'ReportDashboard' order by name,VersionNo desc";
$GetVersion = $conn->query($Vsql);
$VersionNumber = $GetVersion->fetch(PDO::FETCH_ASSOC);
$data = $VersionNumber;
echo json_encode($data);
I also added the following script to the previous file with the form:
$("#WebName").change(function ()
{
$.post("UpdateAdminVersion.php",
{
parameter1: "ReportDashboard Dev",
parameter2: $("#VersionNumber").val()
},
function (data, status)
{
aconsole.log(data)
$("#Notes").val(data);
});
});
I must still be missing something because nothing happens when I change the drop down.
UPDATE 2
I've changed the script to this:
$("#WebName").change(function ()
{
$.post("UpdateAdminVersion.php",
{
WebName: $('#WebName').val(),
VersionNumber: $("#VersionNumber").text()
},
function (data, status)
{
console.log(data)
$("#Notes").val(data);
success: alert ("Number 2 is successful!");
});
success: alert ("Number 1 is successful! \n" + WebName + "\n" + VersionNumber);
});
I get the alert Number 1 is successful!, but the WebName and VersionNumber variables return [object HTMLSelectElement] and [objectHTMLInputElement] respectively. How do I return the actual values?
And how do I use them in the UpdateAdminVersion.php file?
For starters you can use jqueryUI Autocomplete to feed Select tag with options.
Then use onchange event to capture dropdown changes.
<select onchange="myFunction()">
when event is triggered retreive data from db using Ajax, on success modify your form fields accordingly.
Look at this Fiddle give your own parameters, should work.
I'm trying to create an e commerce website for my semester project, but i cant seem to understand the problem with this code.I'm trying to take input from the admin regarding product name,image,details etc and then sending it to php code for processing and submitting it to the database,but the form isn't submitting anything.Here's the code:
<form action="inventory_list.php" method="post" name="f1" enctype="multipart/form-data">
Product Name:<input type="text" id="product_name" size="60" ><br>
Cost:<input type="text" size="10" id="product_cost" style="border:1px solid #c3c3c3;"><br>
Category:<select id="category" >
<option value="Watches">Watches</option>
<option values="Footwear">Footwear</option>
<option value="Apparels">Apparels</option>
</select><br>
Sub-Category:<select id="sub_category" >
<option value="Men">Men</option>
<option values="Women">Women</option>
</select><br>
Product Details:<textarea id="product_details"name="textarea" cols="60" rows="5" wrap="soft"></textarea><br>
Stock:<input type="text" size="10" id="stock" style="border:1px solid #c3c3c3;"><br>
Product Image:<input type="file" id="image"><br>
<input type="submit" id="submit" value="Add Item"><br>
</form>
and this my php code:
if(isset($_POST['product_name'])){
$product_name=mysql_real_escape_string($_POST['product_name']);
$product_cost=mysql_real_escape_string($_POST['product_cost']);
$category=mysql_real_escape_string($_POST['category']);
$sub_category=mysql_real_escape_string($_POST['sub_category']);
$product_details=mysql_real_escape_string($_POST['product_details']);
$stock=mysql_real_escape_string($_POST['stock']);
//Check if product already exists in the database
$sql=mysql_query("SELECT * FROM products WHERE product_name='$product_name'");
$row_count=mysql_num_rows($sql);
if($row_count>0){
echo 'Product already exists in the database,Back';
}else{
//Add this product to database
$sql2=mysql_query("INSERT INTO products (product_name, price, details, category, subcategory, stock, date_added) VALUES('$product_name','$product_cost', '$product_details', '$category', '$sub_category', '$stock', now())")or die(mysql_error());
$pid=mysql_insert_id($sql);
//UPload image to new folder
$newname="$pid.jpg";
move_uploaded_file($_FILES['image']['tmp_name'],"E:\Applications\Xampp\htdocs\The Store\Main\inventory_images/{$newname}");
header("location:inventory_list.php");
exit();
}
}
Any help is appreciated..
On your HTML form, each input needs a name as well as an id:
Product Name:<input type="text" id="product_name" size="60" ><br>
Should be:
Product Name:<input type="text" id="product_name" name="product_name" size="60" ><br/>
Every one of your inputs needs a name. The $_POST array derives from the input names, so they all need to match your PHP code as well. Also note #Loz Cherone's comment. Mysql functions are deprecated, and open you up to a variety of nasty attacks.
So Ive been going trough your project since there is nothing to do today at work and I noticed a couples of things.
First of all, like lars said, a POST use the name of the form to get his data, not the ID.
You also had some typos in your SELECT list where ''value'' where written ''values''.
So I change your code a little bit and you only have to make sure that you can connect to your DB and your set !
<form action="inventory_list.php" method="post" name="f1" enctype="multipart/form-data">
Product Name:<input type="text" name="product_name" size="60" ><br>
Cost:<input type="text" size="10" name="product_cost" style="border:1px solid #c3c3c3;"><br>
Category:<select name="category">
<option value="Watches">Watches</option>
<option value="Footwear">Footwear</option>
<option value="Apparels">Apparels</option>
</select><br>
Sub-Category:<select name="sub_category">
<option value="Men">Men</option>
<option value="Women">Women</option>
</select><br>
Product Details:<textarea name="product_details" cols="60" rows="5" wrap="soft"></textarea><br>
Stock:<input type="text" size="10" name="stock" style="border:1px solid #c3c3c3;"><br>
Product Image:<input type="file" name="image"><br>
<input type="submit" id="submit" value="Add Item"><br>
and your inventory_list.php
if(isset($_POST['product_name'])){
$product_name=mysql_real_escape_string($_POST['product_name']);
$product_cost=mysql_real_escape_string($_POST['product_cost']);
$category=$_POST['category'];
$sub_category=$_POST['sub_category'];
$product_details=mysql_real_escape_string($_POST['product_details']);
$stock=$_POST['stock'];
$sql=mysql_query("SELECT * FROM products WHERE product_name='$product_name'");
$row_count=mysql_num_rows($sql);
if($row_count>0){
echo 'Product already exists in the database,Back';
}else{
//Add this product to database
$sql2=mysql_query("INSERT INTO products (product_name, price, details, category, subcategory, stock, date_added) VALUES('$product_name','$product_cost', '$product_details', '$category', '$sub_category', '$stock', now())")or die(mysql_error());
$pid=mysql_insert_id($sql);
//UPload image to new folder
$newname="$pid.jpg";
move_uploaded_file($_FILES['image']['tmp_name'],"E:\Applications\Xampp\htdocs\The Store\Main\inventory_images/{$newname}");
header("location:inventory_list.php");
exit();
}
}
Hope it helps !
I have been trying to update a field. Bid price and offer price are the fields I want to update. The selections are gbp/usd, eur/usd, etc. I would like to define the text field with variables like $bid, $bid1, bid2, etc. which are already predefined. Can someone help me with this?
This is my code.
<?php
$timestamp=time();set_time_limit (0);
?>
<!DOCTYPE html>
<head></head>
<body>
<meta charset="UTF-8">
<form action ="price.php" method="post">
<p>Symbol : <select name="currency_pair">
<option value="gbp/usd">GBP/USD</option>
<option value="eur/usd">EUR/USD</option>
<option value="usd/cad">USD/CAD</option>
<option value="usd/chf">USD/CHF</option>
<option value="usd/jpy">USD/JPY</option>
<option value="eur/chf">EUR/CHF</option>
<option value="eur/jpy">EUR/JPY</option>
<option value="aud/usd">AUD/USD</option>
</select></p>
<p> Date : <input type="datetime" value="<?php echo date("Y-m-d ",$timestamp); ?>" name="date"/> </p>
<p> Type : <input type="radio" name="type" value="buy">Buy
<input type="radio" name="type" value="sell">Sell
<p> Size : <input type="number"pattern="[0-9]+([\.|,][0-9]+)?" step="0.01"name="size"/></p>
<p> Bid Price : <input type="number" step="any" readonly name="entry" value="<?php if ($currency_pair=="gbp/usd"){echo bid;}elseif($currency_pair=="eur/usd"){echo bid2;};?>" >
Offer Price<input type="number" step="any" readonly="yes" name="entry" value="<?php if ($currency_pair=="gbp/usd"){echo bid;}elseif($currency_pair=="eur/usd"){echo bid2;};?>" ></p>
<p> Stop Loss : <input type="number"step="any" name="stoploss"/></p>
<p> Take Profit : <input type="number"step="any"name="takeprofit"/></p>
<input type="submit" value="Submit"/>
</form>
<script>
</script> </body> </html>
Here is PHP-preprocessed version of the code, which contains only HTML and JS:
<!DOCTYPE html>
<head></head>
<body>
<meta charset="UTF-8">
<form action ="price.php" method="post"/>
<form>
<p>Symbol : <select name="currency_pair" id="select_pair" onchange="pair_selected()">
<option value="gbp/usd">GBP/USD</option>
<option value="eur/usd">EUR/USD</option>
<option value="usd/cad">USD/CAD</option>
</select></p>
<script>
var courses = {};
courses['gbp/usd'] = [ 10, 15 ];
courses['eur/usd'] = [ 14, 16 ];
courses['usd/cad'] = [ 21, 23 ];
function pair_selected() { // to change your edits
var e = document.getElementById("select_pair");
var pair = e.options[e.selectedIndex].value;
var course = courses[pair];
document.getElementById("bid").value = course[0];
document.getElementById("offer").value = course[1];
}
window.onload = function() { pair_selected(); } // to init your edits
</script>
<p> Date : <input type="datetime" value="1970-01-01 " name="date"/> </p>
<p> Type : <input type="radio" name="type" value="buy">Buy
<input type="radio" name="type" value="sell">Sell
<p> Size : <input type="number"pattern="[0-9]+([\.|,][0-9]+)?" step="0.01"name="size"/></p>
**<p> Bid Price : <input id="bid" type="number" step="any" readonly name="entry" value="" >
Offer Price<input id="offer" type="number" step="any" readonly="yes" name="entry" value="" ></p>**
<p> Stop Loss : <input type="number"step="any" name="stoploss"/></p>
<p> Take Profit : <input type="number"step="any"name="takeprofit"/></p>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Tested and works in IE 8-10, Firefox, Chrome, Opera 15 and Safari
First, you need to get a framework. The most commonly used framework is jQuery.
Secondly, I would look here for the code on how to get the selected text: jQuery Get Selected Option From Dropdown
Finally, you should bind the relvant code to the corresponding event. In jQuery that is the change() event.
Example
$('#currency_pair').change(function() {
// Note: 'currency_pair' should be an ID, not a name.
$('#textBox').text($('#currency_pair').val());
});
This should go in a separate file, and it should be linked into your HTML via the script tag, which you can find a tutorial on here: http://www.w3schools.com/tags/att_script_src.asp
It is answered here:
Change input class of textbox onchange dropdown List
Play around the code to check what works for you.
You should use one PHP array, not separate variables $bid, $bid2, ...
You should generate Javascript data structure (object of arrays in code below, but this can vary) from your PHP array
You should use event onchange of your select to lookup Javascript data structure, find there appropriate data (for user selection) and substitute it into your edits
Learning and using framework like jquery instead of pure JS would be simpler and better, so it is recommended, but not obligatory. Code below is using only pure JS, because you did not mention knowledge or usage of any framework in your question.
Here is the code:
<?
$timespamp = time();
$conversions = array(
"gbp/usd" => array(10,15),
"eur/usd" => array(14,16),
"usd/cad" => array(21,23)
// and so on
);
?>
<!DOCTYPE html>
<head></head>
<body>
<meta charset="UTF-8">
<form action ="price.php" method="post"/>
<form>
<p>Symbol : <select name="currency_pair" id="select_pair" onchange="pair_selected()">
<? foreach( $conversions as $pair=>$course ) { ?>
<option value="<?=$pair?>"><?=strtoupper($pair)?></option>
<? } ?>
</select></p>
<script>
var courses = {};
<? foreach( $conversions as $pair=>$course ) { ?>
courses['<?=$pair?>'] = [ <?=$course[0]?>, <?=$course[1]?> ];
<? } ?>
function pair_selected() { // to change your edits
var e = document.getElementById("select_pair");
var pair = e.options[e.selectedIndex].value;
var course = courses[pair];
document.getElementById("bid").value = course[0];
document.getElementById("offer").value = course[1];
}
window.onload = function() { pair_selected(); } // to init your edits
</script>
<p> Date : <input type="datetime" value="<?php echo date("Y-m-d ",$timestamp); ?>" name="date"/> </p>
<p> Type : <input type="radio" name="type" value="buy">Buy
<input type="radio" name="type" value="sell">Sell
<p> Size : <input type="number"pattern="[0-9]+([\.|,][0-9]+)?" step="0.01"name="size"/></p>
**<p> Bid Price : <input id="bid" type="number" step="any" readonly name="entry" value="" >
Offer Price<input id="offer" type="number" step="any" readonly="yes" name="entry" value="" ></p>**
<p> Stop Loss : <input type="number"step="any" name="stoploss"/></p>
<p> Take Profit : <input type="number"step="any"name="takeprofit"/></p>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
<form name="search" method="post" >
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="category1">category1</option>
<Option VALUE="category2">category2</option>
</Select>
<input type="submit" name="search" value="Search" />
</form>
<?php
if(!empty($_POST)){
$options = array('category1'=> array('1' => 'dog', '2' => 'cat'), 'category2' =>array('1'=>'flower', '2'=>'grass'));
$input = trim($_POST['find']);
$category = $_POST['field'];
$output = $options[$category][$input];
echo $output;
}
?>
Question:
if i input 1 and select 'category2', it shows:flower, but the input filed became empty, and select box went back to 'category1', is there a way that i can let input box and select box keep the value i put there, in my case, after i click submit botton, '1' still is in input field, and 'category2' shows in select box.
Use value="<?php if(isset($_POST[])) echo $_POST[]; ?>"
<form name="search" method="post" >
Seach for: <input type="text" name="find" value="<?php echo (isset($_POST['find']) ? $_POST['find'] : ''); ?>" /> in
<Select NAME="field">
<Option VALUE="category1" <?php echo (isset($_POST['field']) && $_POST['field'] === 'category1') ? 'selected="selected"': ''; ?>>category1</option>
<Option VALUE="category2" <?php echo (isset($_POST['field']) && $_POST['field'] === 'category2') ? 'selected="selected"': ''; ?>>category2</option>
</Select>
<input type="submit" name="search" value="Search" />
</form>
Let's say this is your username input/form
<input type="text" name="username" value="" />
now inside where it says value="", You have to put PHP code to be remembered if someone posts something. Much like:
<?php if(isset($_POST['username'])) echo $_POST['username']; endif ?>
which means, if a persone already submits a username, it will stay there, else, it will just be empty.
You could create a little function though, instead of putting that much of code inside,