retain select option values in php - php

I am unable to figure it out on how to retain select option value after submission. I have looked at various forums and self-help sites:
store drop down options in mysql database, PHP1
http://www.tizag.com/mysqlTutorial/mysqlinsert.php
insert value of html select form into mysql database
Using $_POST to get select option value from HTML
Yet, when refresh the page after selecting the dopwdown options, it wasn't able to retain the last selected value:
Select PHP codes:
$dropdown = elgg_echo('<DIV align="left", >
<form method="post" action="Select.php">
<select name="mycustomFile" >
<option>Select Value..</option>
<option value="A">a</option>
<option value="B">b</option>
<option value="C">c</option>
<option value="D">d</option>
</select>
<p><input type="submit" value="Submit"</p>
</form>
</DIV>');
2nd Code: Select.php (where I perform $_POST[''] action)
<?php
/**
* Override the ElggFile
*/
class FilePluginSelect extends ElggObject {
protected function initializeAttributes() {
parent::initializeAttributes();
$this->attributes['customFile'] = "my_select";
}
public function __construct($guid = null) {
parent::__construct($guid);
}
public function customFile(){
//method to call on model to allow select option
//To post select option into mysql database
$selectOption =$_POST['mycustomFile'];
if(isset($selectOption)){
$sql = "INSERT INTO Entries (mycustomFile) VALUES (".$_POST['selectOption'].")";
}else { // User selected nothing
echo 'No options selected!';
}
}
}
Could someone please help to enlighten me what has gone wrong. Thanks

You're doing it completely wrong. You probably just should use Elgg data model and store your value in metadata unless you have very good reason to ignore framework and do stuff on your own.
First of all don't bother extending ElgObject, you're doing it completely wrong and don't really need it.
To retain selection, you have to read the value and mark tag with selected attribute.
You need to update also action of saving file to include new field value. To save it to metadata you just need to use EAV interface of the entity (you'll find example in http://learn.elgg.org/en/1.12/tutorials/blog.html). Than you can read it within the view you're extending
As for the select element itself, you should use existing input/dropdown view instead. It will save you some boilerplate code. Also no need to add tag as you should be extending existing form view. Views documentation is here: http://learn.elgg.org/en/1.12/guides/views.html
I strongly recommend starting your search in Elgg documentation first. Elgg does have some learning curve, but you want to learn the proper way for your code to be maintainable in future.

set mycustomFile to mycustomFile[] . Also don't post anything into the database without clearing it, its very dangerous.
update:
Your php for getting the value of the select form is correct. Your script isn't working for another reason. Here is a sample of retrieving the select fields data.
<?php
if(isset($_POST['button']))
{
echo 'select value: ' . $_POST['something'];
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="something">
<option value="a">some a</option>
<option value="b">some b</option>
<option value="c">some c</option>
</select>
<button name="button">
click
</button>
</form>
</body>
</html>

Related

PHP Setting select as variable

How can i make piece of select statement as php variable?
Example:
I have 2 options in select statement - edit and delete... I have those 2 options in dropdown menu... I want to make an mySQL query to edit or delete records/users from database...I tried to use switch and cases but it only gave me default as selecting.
<select name="editSelector">
<option name='edit'>Edit</option>
<option name='delete'>Delete</option>
</select>
<?php
if (select == edit)
{
edit query here
}
elseif (select == delete)
{
delete query here
}
?>
I know that this code doesn't have any variables etc. Because i have no idea how to make option as variable. It's connected to database already. Thanks for the answer in advance.
<?php
if($_REQUEST['editSelector'] == "edit"){
edit here;
}
else if ($_REQUEST['editSelector'] == "delete"){
delete here;
}
?>
Plus :
<select name="editSelector">
<option value='edit'>Edit</option>
<option value='delete'>Delete</option>
</select>
you need to place your select > option list in a form and process it the proper way using POST.
I would strongly advise against using ajax to facilitate any crud activity in your database. Unless you know what youre doing its VERY insecure.
heres a reasonable web resource if you need to look things up.
HTML file
<form name='option_form' action='someProcessingFile.php' method='post'>
<select name="editSelector">
<option value='edit'>Edit</option>
<option value='delete'>Delete</option>
</select>
<input type='submit' name='submit' value='Submit'/>
</form>
someProcessingFile.php
<?php
if(isset($_POST['editSelector']) {
switch($_POST['editSelector']) {
case 'edit':
// do something here, probably with the rest of the form
break;
case 'delete':
$id = htmlspecialchars($_POST['id']);
// do something here and delete the entry
break;
default:
// do something here to let yourself know that it all went wrong for some reason.
}
}

Adding error message when a specific drop down option is selected

Ok guys, Ive done some researching and can't find something that works to solve my problem even though I'm sure its a simple fix :)
I have a simple contact form in which the first line is a drop down selection. This drop down determines which employee the form is submitted to. I just want to make my default option of "Please Select Category" return an error message so that the submitter must go back and select one of the options to get the form sent. When nothing is selected, its creating a lot of junk mail to the default email.
Here is the drop down bit of code:
<tr>
<td><label for="sendTo">Category (required):</label></td>
<td>
<select id="sendTo" name="sendTo">
<option id="pleaseSelectcategory1" value="pleaseSelectcategory1">Please Select Category</option>
<option id="aftermarketCustomerservice" value="aftermarketCustomerservice">Aftermarket Customer Service</option>
<option id="technicalAssistance" value="technicalAssistance">Technical Assistance</option>
<option id="aftermarketSales" value="aftermarketSales">Aftermarket Sales</option>
<option id="performanceProducts" value="performanceProducts">Performance Products & Sales</option>
<option id="oemSales" value="oemSales">OEM Sales</option>
<option id="exportSales" value="exportSales">Export Sales</option>
<option id="generalFeedback" value="generalFeedback">General Feedback</option>
</select>
</td>
</tr>
I just need what to put in my html, if anything, to make this error message occur and in my php file. Thanks in advance!!
You should use a Javascript function to validate your form prior to posting the data. This is better for UX, and will prevent the form from even reaching the PHP post function.
In your form have the onsubmit field call a Javascript function:
<form name="form" id="form" action="" onsubmit="return validateForm()" method="POST">
and your Javascript function for checking the select box value:
// Basic form validation for select box.
function validateForm() {
if (document.getElementById("sendTo").value != null && docmument.getElementById("sendTo").value != "pleaseSelectcategory1") {
return true;
}
//Handle error message here.
alert("Please select a category");
return false;
}
You can also validate your form once the form gets posted in PHP with:
if ($_POST['sendTo'] === 'pleaseSelectcategory1') {
// Redirect back to form or do whatever
}
In pure JavaScript you can use the following function:
function checkCategory(){
if(document.getElementById('sendTo').value === 'pleaseSelectcategory1') {
alert("You need to select category");
//This is to ensure that the form doesn't get submitted.
return false;
}
}
Either use onclick="javascript:checkCategory();" on the button or the form itself onsubmit="javascript:checkCategory();"
In PHP you can just use:
if($_POST['sendTo'] == "pleaseSelectcategory1")
{
//However you want to handle the the fact the user selected the option
}

Remembering php form data to display currency all over a website

I've set up a currency conversion dropdown in a wordpress site.
The only thing missing is that every time I load another page, the currency will reset as the form selection was 'forgotten'.
Any ideas how to do this? I tried a suggested js cookie that I saw here, but it doesn't work.
This is what I got so far:
<form name="myform" id ="myform" method="post">
<select name="currency-select" id="sort" onchange="submitform();">
<option value="" selected="selected">Currency</option>
<option value="0">U.S Dollars (USD)</option>
<option value="1">Euros (EUR)</option>
<option value="2">British Pounds (GBP)</option> `
</select>
</form>
js:
function submitform()
{
document.myform.submit();
}
I tried using this code as recommended here but it doesn't really work out for me, I think I didn't do it the right way -
<?php
`session_start();`
if (isset($_POST['currency-select'])) {
$_SESSION['sort'] = $_POST['sort'];
}
?>
I added the $_SESSION to the form as well:
<option value="0" <?php if($_SESSION['sort'] == "0") echo "selected";?>>U.S Dollars (USD)</option>
UPDATE
I've made a few tests. The session seems to be saved (as I echoed it on a few pages while refreshing etc.) I guess the only problem now is related to the form itself. Even with the right session number, I can't get it to select the right option.
I've tried two methods, but both does not work:
<option value="0" <?php if($_SESSION['currency-select'] == "0") echo 'selected="selected"';?>>U.S Dollars (USD)</option>
or
<option value="0" <?php if($_SESSION['currency-select'] == "0") echo "selected";?>>U.S Dollars (USD)</option>
I'd store the selected value in a $_SESSION['selected_currency'] variable and the cross check and select it when the drop down is being populated with the currency list.
Assuming that the sessions are working, I will use something like below to keep the currency selected in your drop down.
<select name="currency">
<?php
foreach($currency as $value){
if($value->currency_code == $_SESSION['currency']){
echo "<option value='$value->currency_code' selected='selected'>$value->currency_name</option>";
} else {
echo "<option value='$value->currency_code'>$value->currency_name</option>";
}
}
?>
</select>
There could be shorter ways, I am using this for illustration purposes.
For permanent retain of data you only have a few possibilities, the easiest to implement are $_SESSION, $_COOKIE or in a Database.
You have two options to do that
1st is by adding a field to the options.php page and save your data then get back your data from the options.php for that you've to use update_option('nameOfField_form','nameOfFieldDb'); and get_option('nameOfFieldDb').
and 2nd option is by jquery.ajax(); method save your data in options.php
you may find these links helpful codex
get_option
update_option

Getting value and text of Select Option with PHP

I have a list of organizations in a DDL where the Text displays the full name of each organization and the Value is the key for that organization. I need both the full name and the key entered into my database when an organization is selected. I have been unable to access both the Value and the Text using PHP, so I ended up stringing the full name and key together in the Value field and using Explode to split them into different variables (see below). Is this the best way to do this? I want to make sure I'm not overlooking something cleaner and simpler.
HTML:
<form method="post" action="submit.php" name="requestDetailsForm">
<label>Organization Name:</label>
<select id="org_name" name="org_name">
<option value="Organization 1.abc">Organization 1</option>
<option value="Organization 2.def">Organization 2</option>
</select>
<input type="Submit" value="Submit">
</form>
PHP:
<?php
$org_name = mysql_escape_string($_POST['org_name']);
$org_name_split = explode('.', $org_name);
$org_name_full = $org_name_split[0];
$org_name_key = $org_name_split[1];
$strSQL = "INSERT INTO Database(org_name_full, org_name_key) VALUES ('$org_name_full', '$org_name_key')";
?>
I would use jQuery to do this one, I would add a hidden element and assign the value as the option's text value on form submission.
<form method="post" action="submit.php" name="requestDetailsForm">
<label>Organization Name:</label>
<select id="org_name" name="org_name">
<option value="Organization 1.abc">Organization 1</option>
<option value="Organization 2.def">Organization 2</option>
</select>
<input type='hidden' name='option_text'value='' >
<input type="Submit" value="Submit">
</form>
<script type="text/javascript">
$('form').on('submit', function(e){
e.preventDefault();
var text = $('#org_name').find(":selected").text();
$('input[name="option_text"]').val(text);
$('form').submit();
});
</script>
There is no way to access both the selected value and the name through something like the $_POST array.
However, what I would generally do in a situation like this is create a table in the database of all possible organizations with their names and codes. In PHP, I would generate the list of select options using SELECT * on that database when generating the HTML for the original page. Then, when the data is submitted you just insert the organization code into the second table that you're dealing with. When you need to know the full organization code and name associated with the record in that table, you use a JOIN statement.
For example, say the original database that you're dealing with now represents users and each user has an organization. When someone submits the form, you insert a new user record into that table and insert the organization code into an organization_id field in that same users table. Then, when you want to know the organization code and name for a given user, you do SELECT * FROM users LEFT JOIN organizations ON user.organization_id = organization.id WHERE user.id = blah. This will return the user record along with their organization code and name.
This is the best way when only using PHP.
A possible improvement could be to improve how you split the POST in variables:
list($org_name_full, $org_name_key) = explode('.', $org_name);
Otherwise you should use javascript to add either variable you need to the post

Pass values from Javascript to script PHP, and generate JSON to other page

I'm doing an android app in eclipse (using phonegap + json + php) and i have some troubles... I really don't know how to ...
I have a php file (consulta.php) that generates the json, whichc is locate in my server (192.168.1.200/test/consulta.php:
header('content-type: application/json');
mysql_connect("localhost","jhonatan","jsandoval");
mysql_select_db("tesis");
$array = array();
$query = mysql_query("SELECT * FROM GRIFO");
while($fila = mysql_fetch_object($query)){
//echo $fila['id'] . " " . $fila['grifo'] . " " . $fila['distrito'] . "<br/>";
$array[] = array('id'=>$fila->id,
'grifo'=>$fila->grifo,
'distrito'=>$fila->distrito,
'latitud'=>$fila->latitud,
'longitud'=>$fila->longitud);
}
echo json_encode($array);
So, in my index.html (from android app, phonegap in eclipse) , have a form wich gets 2 selects (HTML).
<form id="combustibleForm" method="get">
<select id="combustibleSelect" name="combustibleSelect" data-theme="a">
<option value="gnv" >Gas Natural Vehicular</option>
<option value="glp" >Gas Licuado de PetrĂ³leo</option>
</select>
<br/>
<select id="distritoSelect" name="distritoSelect" data-theme="a">
<option value="SJL" >San Juan de Lurigancho</option>
<option value="Miraflores" >Miraflores</option>
<option value="Chorrillos" >Chorrillos</option>
<option value="Surquillo" >Surquillo</option>
</select>
<br/>
<input type="submit" data-role="button" id="continuarBtn" value="Continuar.." />
</form>
I must pass the values of these selects to the php file above and generate a json from there:
// GET THE VALUE OF THE SELECTS ... I don't know if this is correct? :S
$tipo = $_GET['tipo'];
$distrito = $_GET['distrito'];
...
...
$query = mysql_query("SELECT * FROM GRIFO WHERE (tipo='$tipo' and distrito='$distrio')");
...
...
// Generate json
echo json_encode($array);
This is what i have to do:
After that... i have another html page (mapa.html, in eclipse), that get the json from the php (wtf!? ) ... HOW TO DO THIS? :S ..
Also, when i Click the submit form (in index.html), must redirect to mapa.html , to get the json....
I really don't know and don't have any ideas to do this big problem...
Can someone please help me?...
Sorry for bad english
Your form element in the HTML has no action attribute. This is where the browser will send the request when the user clicks on submit. So, if you want to send the request to your PHP script you will need you need to set that in the action attribute of your form.
Assuming consulta.php is located in the same directory as that of your HTML page...
<form id="combustibleForm" method="get" action="consulta.php">
<select id="combustibleSelect" name="combustibleSelect" data-theme="a">
<option value="gnv" >Gas Natural Vehicular</option>
<option value="glp" >Gas Licuado de PetrĂ³leo</option>
</select>
<br/>
<select id="distritoSelect" name="distritoSelect" data-theme="a">
<option value="SJL" >San Juan de Lurigancho</option>
<option value="Miraflores" >Miraflores</option>
<option value="Chorrillos" >Chorrillos</option>
<option value="Surquillo" >Surquillo</option>
</select>
<br/>
<input type="submit" data-role="button" id="continuarBtn" value="Continuar.." />
</form>
Now, when this form is submitted the request will be directed to your PHP script, which will generate the JSON.
As for getting the values sent by the form in your PHP you need to use the name attributes you defined for those SELECT elements.
In your case that is combustibleSelect and distritoSelect.
$_GET['combustibleSelect']; // This will be the value of the 1st SELECT box
$_GET['distritoSelect']; // This will be the value of the 2nd SELECT box
Please do not use the old ext/mysql API to interface with your database as it has been deprecated and may be removed in future versions of PHP. Consider using the newer PDO or MySQLi APIs instead to interface with your MySQL databse in PHP.
As for getting the data into javascript, you want to use ajax to make an XHR request to your PHP script. This will allow you to populate whatever you want to populate in the DOM of your HTML with javascript, by asking javascript to go out and make a request to your PHP script in the background and then hand you back the JSON to do with as you please without the user ever having to leave the page.
You could pass the json as an url_encoded string appended to the url or a hidden field. if you need to communicate beteween pages, have the generating page echo the json into a hidden field. You could also do ajax or curl request for the json
Something like (in index.html)
<?php $data = url_encode(json_encode($array)) ?>
<form action="mapa.html?data=<?php echo $data?>" method="get">
...
</form>

Categories