how to let the form remember the values i put - php

<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,

Related

Adding data to wordpress database using template

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>`

How to update a forms text fields when a drop gets updated using php

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.

Three page sequence of forms (checkboxes and text/number boxes) with foreach in php

I would like to pass variables through 3 pages. The 1st page asks the user which music genres they like (there will eventually be 20+ genres). The 2nd page asks the user to rank the genres they have selected and the 3rd page sorts and displays their ranking.
This first page asked the user to pick which genres they like:
<form id="genre" name="genre" method="post" action="musicsell.php">
<input type="checkbox" name="genre[]" value="Rap"/>Rap<br />
<input type="checkbox" name="genre[]" value="HipHop"/>HipHop<br />
<input type="checkbox" name="genre[]" value="RnB"/>RnB<br />
<input type="checkbox" name="genre[]" value="Rock"/>Rock<br />
<input type="checkbox" name="genre[]" value="Jazz"/>Jazz<br />
<p>
<input type="submit" value="Next">
<br />
</p>
</form>
This second asks them to rank (prioritize) the genres they have selected with 1 being the best:
<body>
The genre(s) you selected are: <br>
<form id="form1" name="form1" method="post" action="musicresults.php">
<?php
$name = $_POST['genre'];
if(isset($_POST['genre'])) {
foreach ($name as $genre){
?>
<input
type="number" required="required" id="<?php echo $genre ?>" name="music[<?php echo $genre ?>]" />
<?php echo $genre ?><br />
<?php
}
}
?>
<input type="submit" name="button" id="button" value="Submit" /></form>
</body>
The third and last page sorts and echos the results:
<?php
//Get the form results (which has been converted to an associative array) from the $_POST super global
$musicgenres = $_POST['music'];
//Sort the values by rank and keep the key associations.
asort($musicgenres, SORT_NUMERIC );
//Loop over the array in rank order to print out the values.
foreach($musicgenres as $music => $rank)
{
echo "$musicgenres is your $rank choice";
echo "<br>";
}
?>
It all works fine until the last page where I'm getting an "array to string conversion" error. Maybe I need to put in session variables but I'm not sure.
Any help would be appreciated.
It's exactly what the error says. It can't convert and array to a string.
Replace
echo "$musicgenres is your $rank choice";
with
echo "$music is your $rank choice";

How to use POST and GET method in the same page, and pass all variables to next page by pressing button?

In current code, I have POST and GET method on the same php page(delivery.php) as shown below.
What I would like to achieve is that passing following items1-5 to next page(payment.php) by pressing button (Go to payment page).
item1; request (this is coming from previous page)
item2; name (user's input)
item3; shippingfee (shown in span tag in the code, and this is the value returned back from shipping.php by GET method)
item4; address(user's input)
item5; email(user's input)
How can I achieve that?
delivery.php
<?php
$request = $_POST['request'];
?>
<html>
....
<form name="aaa" method="POST" action="payment.php">
<input name="name"></input>
</form>
<form name="bbb" method="GET" action="shipping.php">
<select id="country" name="countryshipping">
<option value="null" select="selected">default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
<form name="ccc" method="POST" action="payment.php">
<input name="address"></input>
<input name="email"></input>
</form>
....
<div>
<span id="shippingfee"></span>
</div>
....
<form ????????>
<button type="submit">Go to payment page</button>
</form>
....
Solution
I could manage to achieve what I wanted to do. Sharing my code:
delivery.php
<?php
$request = $_POST['request'];
?>
<html>
....
<form name="aaa" method="POST" action="payment.php">
<input name="name"></input>
<select id="country" name="countryshipping">
<option value="null" select="selected">default</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input name="address"></input>
<input name="email"></input>
</form>
....
<div>
<input type="hidden" name="shippingfee" id="shippingfee2"><span id="shippingfee"></span>
</div>
....
<button type="submit">Go to payment page</button>
</form>
....
Payment.php
<?php
$name = $_POST['name'];
$country = $_POST['countryshipping'];
$address = $_POST['address'];
$email = $_POST['email'];
$shippingfee = $_POST['shippingfee'];
?>
In addition to above codes, I added one line in jQuery
document.getElementById("totalfees2").value = value; // "this value is the same value which is stored in id="shippingfee""
$_REQUEST will deliver all of the get and post vars.
echo $_REQUEST['baz']; // "qux"
echo $_REQUEST['foo']; // "baz"
<form action="script.php?foo=bar" method="post">
<input type="text" name="baz" value="qux">
<input type="submit">
</form>
<?php
echo $_POST['baz']; // "qux"
echo $_GET['foo']; // "baz"
Note that the other way around doesn't work. You can't have a get method form, and get POST data submitted as well.

How do I display data on a text field upon selection of an option in a form

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>

Categories