how select a string in PHP - php

I have a code where I would like to choose between four different possibility:
Query1
Query2
Query3
Query4
Once an user has choose his/her query my code has to execute a specific function in a different php file, the specific function should be activated depending on which index (1,2,3,4 that comes from the relative query) the user has chosen.
For instance if the user has chosen the Query1 the function:
function a($index){
}
where $index is 1, obtained directly form the query chosen.
Could you help me?
Thanks in advance

The Code Below might come in handy. The Idea here is that you Check within PHP if the Form was Submitted.... if it was, then simply get the Value of the Query (like: 1, 2, 3, 4). Then using Switch statement, You may then determine for yourself which Function should be called based on those Values: 1, 2, 3 and 4 respectively. NOTE: Be sure those functions are defined in your PHP Script as well...
<?php
if(isset($_POST['run'])){
$queryKey = isset($_POST['query']) ? $_POST['query'] : null;
if($queryKey){
switch($queryKey){
case "1":
callableFunctionForQuery1();
break;
case "2":
callableFunctionForQuery2();
break;
case "3":
callableFunctionForQuery3();
break;
case "4":
callableFunctionForQuery4();
break;
default:
}
}
}
?>
<html>
<head>
</head>
<body>
<form name="query-processor" action="" method="POST">
<label for="query" class="lbl" id="lbl-query">Please Select a Query to Run</label>
<select name="query" class="form-control" id="query">
<option value="1">Query1</option>
<option value="2">Query2</option>
<option value="3">Query3</option>
<option value="4">Query4</option>
</select>
<input type="submit" value="Run" id="run" name="run" />
</form>
</body>
</html>

OK so i think what you want is to assign a function to a variable
$function = function()
{
echo 'executing function';
};
then call the function by using the variable name
$function();

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

PHP random text once

I've been looking for the solution of my problem for ages and I still haven't found it so i desided to create a stackoverflow account to ask the question myself.
this is what I created so far:
<? //Chooses a random number $num = Rand (1,2);
switch ($num){
case 1: $retrieved_data = "test"; break;
case 2: $retrieved_data = "test1"; break;
} ?>
And this is the place where I want the text to appear;
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input name="<?php echo $retrieved_data; ?>" type="file" />
<input name="<?php echo $retrieved_data; ?>" type="file" />
<input type="submit" value="Upload" /></form>
My problem is I want to have the "test1" and "test" randomly displayed on these places
but I want them to be different from eachother every time. So if the first input type is "test" I want the second input type to be 'test1" but I can't seem to get this working
Does anyone know what I'm doing wrong or a code to make this possible?
If you have limited number of possibilities, put them int an array, shuffle it and shift/pop elements from it:
$retrieved_data = array('test', 'test1');
shuffle($retrieved_data);
$random1 = array_shift($retrieved_data);
$random2 = array_shift($retrieved_data);
Step A - you are selecting a number, 1 or 2
Step B - you are running that number through your switch case, this case ONLY takes the number that it receives and assigns it a value. Therefore if your number is 1, your switch case ends at $retrieved_data = "test". If your number is 2 your switch case goes to case 2 and assigns $retrieved_data = "test 1".
Step C = $retrieved_data is assigned to your form (it will have only one value, "test" or "test1".
Use array_rand() for that.
$aName = array('test1', 'test2', 'whatever');
function getRandom(array &$aName)
{
if (($key = array_rand($aName)) === NULL) {
throw new Exception('No more randomness!');
}
$value = $aName[$key];
unset($aName[$key]);
return $value;
}
So simply use getRandom($aName) when you need a unique random item from the array.

Execute Function based on the selection on Drop down list

I am trying to learn php today and I on the part of experimenting. I encountered problem using the drop down list, if and else and the function.
It's seems that its not working. I have no idea how to debug it. What I'm trying to do is that when the user selects "employed", it will simply return a "Do THIS!" text. but if the user selects any of the 3 (self employed, Voluntary member & OFW), it will display "DO THAT!".
It's really simple but i can't get it work, i just started php 6 hours ago. :)
Please help!
<form method="POST">
Salary: <input id="salarytext" type="text" name="salary" onkeypress="return isNumberKey(event)"><br>
Membership Type:
<select name="membershiptype">
<option value="employed">Employed</option>
<option value="SE">Self Employed</option>
<option value="VM">Voluntary Member</option>
<option value="OFW">OFW</option>
</select>
<br/>
<input type="submit" />
</form>
<?php
$a = (isset($_POST['salary'])) ? $_POST['salary'] : '';
$b = (isset($_POST['membershiptype'])) ? $_POST['membershiptype'] : '';
function employed () {
if (empty ($a)) {echo "";}
elseif ($a<10000) {$a * 2.0}
elseif ($a<20000) {$a * 2.3}
elseif ($a<30000) {$a * 2.7}
elseif ($a>30000) {$a * 3.0}
}
function sevmofw() {
if (empty ($a)) {echo "";}
elseif ($a<10000) { $a * 1.3}
elseif ($a<20000) { $a * 1.5}
elseif ($a<30000) { $a * 1.8}
elseif ($a>30000) { $a * 2.0}
}
if ( $_POST['membershiptype'] == 'employed' ){employed();
} elseif ( $_POST['membershiptype'] == 'SE' ){sevmofw();
} elseif ( $_POST['membershiptype'] == 'VM' ){sevmofw();
} elseif ( $_POST['membershiptype'] == 'OFW' ){sevmofw();
}
?>
Here's a flowchart of what i'm trying to do.
<select name="membershiptype" method="POST">
<option value="Employed" name="employed">Employed</option>
<option value="SE" name="sevmofw">Self Employed</option>
<option value="VM" name="sevmofw">Voluntary Member</option>
<option value="OFW" name="sevmofw">OFW</option>
</select>
should be
<select name="membershiptype">
<option value="employed">Employed</option>
<option value="SE">Self Employed</option>
<option value="VM">Voluntary Member</option>
<option value="OFW">OFW</option>
</select>
and your code should be
if (isset($_POST['membershiptype'])) {
if ( $_POST['membershiptype'] == 'employed' ){
employed();
} elseif ( $_POST['membershiptype'] == 'SE' ){
sevmofv();
}
}
...
I want to add this answer, because there is more potential in this topic and you're learning PHP so all bits add up.
Let's start with the PHP Tag. In your .php files you only need to add <?php once at the top and no close tag ?> at the end. Why? See this SO answer https://stackoverflow.com/a/4499749/2493918 .
Then put all the functions you want to be executed via the select in your script:
<?php
/**
* functions.php
*/
function employed()
{
return 'Employed function called.';
}
function sevmofw()
{
return 'Sevmofw function called.';
}
Note here that I replaced the " quotes with single ' quotes. Why? See this answer here:
https://stackoverflow.com/a/3446286/2493918 .
Then create another .php file containing your form (let's call it form.php):
<?php include 'functions.php'; // include the functions ?>
<!DOCTYPE html>
<html>
<head>
<title>Form Function Test</title>
</head>
<body>
<?php
// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset('membershiptype'))
{
// If the requested function exists, call it
if (function_exists($_POST['membershiptype']))
{
$func = $_POST['membershiptype'];
echo $func();
}
}
?>
<form action="" method="POST">
<div>
<label>
Salary: <input id="salarytext" type="text" name="salary" onkeypress="return isNumberKey(event);">
</label>
</div>
<div>
<label>
Membership Type:
<select name="membershiptype">
<option value="employed">Employed</option>
<option value="SE">Self Employed</option>
<option value="VM">Voluntary Member</option>
<option value="OFW">OFW</option>
</select>
</label>
</div>
<div>
<input type="submit" name="submit_btn" value="Submit form">
</div>
</form>
</body>
</html>
You see we include the functions into this forms page. This way you separate the functions from the so called view. Now you could include the same functions on other pages as well.
Then if you use PHP inside HTML you need to use both php tags <?php and ?> to separate the php part from the html.
If you submit the form the php part will check if the form was submitted and if the membershiptype is set. Then it continues and checks if the requested function exists. If so, it calls the function and returns the output.
Remember: It's better to return values inside functions and echo them where you want (see the example above).
A good resource to learn about PHP are the docs which can be found here:
For example the function_exists() documentation page http://www.php.net/manual/en/function.function-exists.php .
Try to switch to a PHP Framework as soon as you can. It'll help you immense. I recommend Codeigniter as it has a thorough documentation and a low learning curve. Later you could switch to something like Laravel, but I tell you, that's too soon now.
Good luck learning PHP :-)
Here's the answer for your help request after the question edit:
First of all, I love flow charts too! It's a clean way to plan a project or function.
I see you've used ternary operators. That's great :-)
Ok, so you've got a good idea of what you want to achieve (flowchart). I'll try to point you into the right direction with an example.
According to your flowchart "start" means the "form". This example shows the php part and expects that the form was submitted with the required data:
<?php
// START - Check if all required data was submitted
if ( isset($_POST['salary'], $_POST['membershiptype']))
{
// Get the form data
$salary = $_POST['salary'];
$member_type = $_POST['membershiptype'];
// USER SELECTS EMPLOYED?
$user_employed = ($member_type == 'employed') ? true : false;
// Create the multiplication table
// for the salary calculations
$multiBy = array(
'10000' => 1.3,
'20000' => 1.5,
'30000' => 1.8,
'30001' => 2.0,
'employed' => array(
'10000' => 2,
'20000' => 2.3,
'30000' => 2.7,
'30001' => 3.0,
),
);
// Create the calculation function
function calcSalary($s = 0, $employed = false)
{
// Use global here so you can access the
// $multiBy array from inside this function
// without the need to pass it separately
// like $s and $employed
global $multiBy;
// Check if $s is specified
if (empty($s)) return false;
// Round the $s value to be able to use
// it as key for the $multiBy array
// PHP Documentation: http://php.net/manual/en/function.round.php
$value = round($s, -4);
// Set the multiplication values
$multi = $multiBy;
if ($employed) $multi = $multiBy['employed'];
if ($value > 30000) $value = 30001;
if ($value < 10000) $value = 10000;
// Calculate the salary and return the result
return $s * $multi[$value];
}
// GET SALARY INPUT
// Putting the result in a var so you can process however you like
$calculated_salary = calcSalary($salary, $user_employed);
// END - Print the calculated salary
echo $calculated_salary;
}
else
{
// I guess this is self-explanatory :P
echo 'Please enter all required data and try again.';
}
This is a basic example. If you're going to accept user input (public form) remember to secure the input. With "secure" I mean htmlentities, CSRF (Cross Site Request Forgery), XSS (Cross Site Scripting), Code Injection (also SQL Injection if you're going to use Databases).
Also don't forget error handling e.g. missing form input (like if( ! isset($_POST['field'])) echo 'ERROR: Missing input'; else ...).
Here are some resources related to php security you might find useful:
PHP Functions…
PHP htmlentities()
PHP htmlspecialchars()
PHP strip_tags()
Articles with code examples…
Ned Batchelder: Xss with utf-7
Cross-Site Request Forgeries by Chris Shiflett
and some StackOverflow Questions:
"Why my code vulnerable to xss attack?"
How to prevent SQL injection in PHP?
Have fun reading and happy coding!

Error javascript function to get value out of static php drop down

I made the dropdown with PHP which works fine. When the selected item changes, I call the function changePeriod().
$options[0] = '--period--';
$options[1] = 'Daily';
$options[2] = 'Weekly';
$options[3] = 'Monthly';
<td><?php echo form_dropdown('period', $options, '0', 'id="period" onchange="changePeriod()"'); ?></td>
Here you can see the HTML source code which is a result of the code above.
<td>
<select name="period" id="period" onchange="changePeriod()">
<option value="0" selected="selected">--period--</option>
<option value="1">Daily</option>
<option value="2">Weekly</option>
<option value="3">Monthly</option>
</select>
</td>
In this function I need to get the value of the selected item, but the 2 alerts above the switch both give Undefined as a result. Does anyone has an idea why I get undefined and not the values of the selected option? It worked with a dynamic dropdown filled with a foreach from the database.
function changePeriod() {
alert(document.getElementById("period").selectedIndex);
alert(document.getElementById("period").value);
switch (document.getElementById("period").selectedIndex) {
case 1:
alert("daily");
break;
case 2:
alert("weekly");
break;
case 3:
alert("monthly");
break;
}
}
Basically: Why can't I get the values of the selected option and how can I fix it?
Thanks for helping.
Is the HTML generated like this:
<select onchange="changePeriod()" id="period">
<option value="0">--period--</option>
<option value="1">Daily</option>
<option value="2">Weekly</option>
<option value="3">Monthly</option>
</select>
<script type="text/javascript">
function changePeriod(event) {
alert(document.getElementById("period").selectedIndex);
alert(document.getElementById("period").value);
switch (document.getElementById("period").selectedIndex) {
case 1:
alert("daily");
break;
case 2:
alert("weekly");
break;
case 3:
alert("monthly");
break;
}
}
</script>
If yes, it works for me.
Why don't you use jquery, you could do everything with less code.
EDIT:
The solution with jQuery:
$("#period").change(function(){
alert("The Value: "+$(this).val());
switch ($(this).val()) {
case 1:
alert("daily");
break;
case 2:
alert("weekly");
break;
case 3:
alert("monthly");
break;
}
});
take a look here: http://jsfiddle.net/rfWjd/

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