PHP Setting select as variable - php

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.
}
}

Related

retain select option values in 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>

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

Language - automatic and by user

I´m trying to play around with languages and an own Database/CMS structure. I´ve got so far, that the Browserset language is selected. This works well. I know there are better solutions (other domains for each language, i´ve google´d a lot)...with an own added cookie (setcookie) it worked, too.
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$langCookie = $_COOKIE['language'];
if(!empty($langCookie)){
$lang = $_COOKIE['language'];
}
if($lang == en){
//Select from database, got three languages, text (en), textOther1 (otherlang1) and textOther2
}elseif($lang == xy){
//other selecet
}else{
//select if nothing fits
}
My problem at this point is:
How can I let the user choose a language with a select on the page. I want to let the user choose the language by a select...but i can´t get it done to set my cookie as I selected an option...
I know that I have got to reload the page after this (header_location), but I can´t get further...
Any help or tipps for solving this would be very nice.
I think you can use the GET method to sent request to a page, just add the language code as a paramter, then check whether this parameter exists -- if not, take your value as it's now.
You can use this markup for example:
<form id="langForm" action="" method="GET">
<select name="lang" onchange="this.form.submit();">
<option value="en">English</option>
<option value="fr">French</option>
</select>
</form>
Then on-server side you should check if lang parameter exists:
<?php
if( isset( $_GET ) && ! empty( $_GET['lang'] ) ) {
// do something
} else {
// do something else
}
?>
Hope that helps!

header('Location: ) in php switch to execute url with onclick function

To put it simply I have this variable which carries a hyperlink:
$test3 = 'Move to Quotes';
and what I need is to execute this variable inside a switch case like below:
switch ($_POST['dropdown']) {
case "Select Folder":
echo "Please select";
break;
case "One":
exec($test3); <-- //here i want to run (if this is not execute, my misunderstanding) the link.
break;
case "Two":
header('Location: http://www.facebook.com/'); <-- //this is just a test
break;
default:
echo "<br></br>";
echo "Move multiple files:";
echo "<br></br>";
}
?>
<form method="post" name="theform" action="">
<select name="dropdown">
<option value="Move to Folder">Select</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<input type="submit" value="Move"/>
</form>
I'd like know how to execute the ahref link without the user clicking it, but simply set this link as a case and when the user submits the form, the selected case actions the hyperlink.
Any help appreciated.
MORE DETAIL
I understand that javascript and php are both seperate languages and that a better option would be to use Ajax, but my understanding of Ajax is limited.
To explain it better, this is what's going on in its entirety:
1) I have a mailbox with a selection of messages.
2) You are able to check these messages and then click a link "Trash Selected" which deletes the selected messages. This the link:
Trash Selected
The javascript function actions the php function in $muldel for all selected messages and updates the database.
This is the javascript function in question:
function inboxDelete(url) {
document.messages.action = url;
document.messages.submit();
}
archiveMove() is exactly the same, just duplicated temporarily to make things clear.
3) I have now re-used the ahref code to do the same procedure, but this time, for moving the selected messages into folders.
4) These folders can be selected from a drop down box - this is where the form comes in.
5) So although I can get it to work by adding a link like such:
$test3 = 'Move to Quotes';
echo $test3;
6) I now need this to work the same way but the link being changed, depending on which folder is selected.
That's the full extent to my problem, I hope this is more clear.
I am aware you can send variables into javscript using GET or POST and then carry out the function entirely through javascript. I have tried something like below, but to no avail:
<form method=post name="myform" action="<?php echo $PHP_SELF;?>">
<input type="hidden" name="formVar" value="">
<input type="text" value="Enter Text Here" name="myText">
<input type="text" value="Enter Text Here" name="myText2">
<input type="submit" value="Send form!" onClick="readmove()">
</form>
<?php
// Retrieve the hidden form variable (using PHP).
$myvar = $_POST['formVar'];
if ($myvar == "$mulmov"){
echo $mulmov;
}
?>
<script language="JavaScript">
<!--
function setText(){
document.myform.myText.value = document.myform.myText.value.toUpperCase();
}
function readmove(){
document.myform.myText.value = "<?php echo $myvar; ?>" ;
readmove2();
}
function readmove2(){
if (document.myform.myText.value == "$mulmov"){
document.myform.myText2.value = "<?php echo $mulmov; ?>" ;
<?php exec ('archiveMove(\''.$mulmov.'\'); return false;'); ?>
} else if (document.myform.myText.value == "$mulmov2"){
document.myform.myText2.value = "<?php echo $mulmov2; ?>" ;
}
}
</script>
First of all, you can't execute JavaScript from within PHP like this. At this point, the control has already moved to the server and JavaScript is run on the client-side.
Second of all Im assuming you dont want to just follow the link, you want to run the link's onClick event, since the href is just a hashtag. So you are trying to run a JavaScript function with PHP. You cant call a function in one language from a function in another language.
Its hard to tell what exactly you are trying to do, but if you want to run a function when a user selects a certain dropdown, write a php function that does what archiveMove() does. If you want this to happen without a page refresh, you can stop the submit process and call your archiveMove() function with javaScript and Ajax.
If elaborate on what exactly you are trying to do, maybe we can help more.
Ok, so the only difference between your working code and the not working code is that you want to dictate the submitted URL based on what is selected in the dropdown?
So you can use JavaScript to set the form action when the dropdown is selected.
BUT, It might be a better idea to submit the form with the same action everytime, and then use PHP to decide what to do. It seems like this is where you were headed initially. Just get the folder id in the switch statement and call a function to make your edits:
The PHP can be similar to the way you had it:
switch ($_POST['dropdown']) {
case "Two":
// set folder id
$folder_id = 2;
break;
}
moveMessages($_POST['Messages'], $folder_id);
function that moves the messages where they need to go.
function moveMessages($messages, $folder_id){
// depending on your form setup
foreach($data as $id => $value ){
if($value){
// code to move to folder
}
}
return true;
}
If there are other factors involved, let me know.
You can write JavaScript code that request a url using window.location.href in click hadler.
window.location.href="http://example.com";
Ok this was my solution but thank you also for your solution Jeff Ryan, this worked also.
<script language="javascript">
function buttons(str)
{
document.getElementById("txtHint").innerHTML = str;
if (document.f1.users.options[1].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
else if (document.f1.users.options[2].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov2; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
}
function submit_mes(str)
{
document.messages.submit();
}
</script>
<form name="f1">
<select name="users" onChange="buttons(this.value)">
<option value="">Select a folder:</option>
<option value="Quotes">Quotes</option>
<option value="Projects">Projects</option>
<input type="button" value="Move" onClick="submit_mes(this.value)">
</select>
</form>
<div id="txtHint"><b>Folder will be listed here.</b></div>

Categories