I have two buttons on my page (yes and no).
I have a function on another page 'choice.php' that updates a database based on this decision. This function takes 'yes' or 'no' as inputs. Therefore I would like each button to run the choice.php page, with 'yes' or 'no' depending on button pressed, and then refresh the current page. Currently I have tried (for 'yes'):
echo "<form></br>";
echo "<input type='button' value = 'yes' Method ='POST' ACTION = 'choice.php'>";
echo "</form>";
But I am unsure where to go from here. The choice.php page has:
function choice('yes'/'no');
The params should be comma separated, but you don't really need params when taking from superglobal array. However, you only need to call the function if 'yes' for example:
<form action="choice.php" method="post">
<input type="submit" name="choice" value="yes" />
<input type="submit" name="choice" value="no" /> <!-- You'd better use radio buttons -->
</form>
<?php
function choice() {
if ($db->query("UPDATE ..... ;")) {
return true;
}
return false;
}
if (isset($_POST['choice']) && $_POST['choice'] == 'yes') {
choice();
}
else {
echo 'no';
}
?>
Ofcourse you can have multiple if's, but I don't think it will help you enough:
if (isset($_POST['choice']) && $_POST['choice'] == 'yes') {
//something;
}
elseif (isset($_POST['choice']) && $_POST['choice'] == 'no') {
//something else;
}
elseif (isset($_POST['choice']) && $_POST['choice'] == 'maybe') {
//something else;
}
If you want the function to update db with the value from the user, you could use something like this:
function choice() {
$choices = array('yes', 'no', 'maybe', 'dunno'); //predefined choices
if (in_array($_POST['choice'], $choices)) { //checks if the user input is one of the predefined choices (yes, no, maybe or dunno)
if($db->query("UPDATE table1 SET userchoice = '{$_POST['choice']}' WHERE user_id = '{$_SESSION['id']}';")) {
return true;
}
}
return false;
}
if (isset($_POST['choice'])) choice(); //so here you don't need (not necessary, but you can) to check if the value is the one you want. If it's set, you call choice(), then the function checks if it's in the array of predefined choices, so if it is - it will update, if it's not it will return false
One way is to use header on your choice.php after your database operations finishes.
header('Location: *where your form page is*');
Another way is to do an ajax post using javascript
Suppose you have something like this:
<form method='POST' action='choice.php'>
<tr>
<td><input type="submit" name="answer" value="yes"></td>
<td><input type="submit" name="answer" value="no"></td>
</tr>
</form>
and in the PHP file you can use the POST method to check for the answer, whether it was yes or no
if($_POST['answer'] == 'yes') {
//do something
}
if($_POST['answer'] == 'no') {
//do something else
}
Related
I am adding a delete button to certain rows of a table (not all). The table is already inside a form, so my thinking is to do a check to see if my button was clicked inside the function that the form submits to and redirect to a delete function if it was. I can't figure out if it's possible to do that or what other options there are.
I tried using a link for the delete, but that doesn't get the information across. I tried using another form, but that's a form within a form. If there is another way to do this, I'm happy to learn it.
Here is parts of the form:
echo '<form action="#/job/addorupdate" id="jobform" name="jobform" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="id" value="228828">';
if ($id > 0) {
echo '<button style="color:red;border:none;font-weight:bold;cursor:pointer;" type="submit" value="' . $id . '" name="idOfRow">X</button>';
}
echo '</form>';
Here is the function it goes to:
public function addOrUpdate(){ // addOrUpdate a job - control
if ($this->input->post('idOfRow')) {
// This is where I want to do the redirect
}
.
.
}
The solution was to replace the button with a link and use that to call the delete function.
echo ' X';
public function addOrUpdate(){ // addOrUpdate a job - control
if ($this->input->post('idOfRow')) {
$delete=deleteRow($this->input->post('idOfRow'));
if($delete == 1){
header('location:location.php'); // add redirect location here.
}
}
}
//Create One New function
public function deleteRow($DeleteInput){
if ($DeleteInput) {
//add sql function to delete
if(delete == true){
return 1;
}
else {
return false;
}
}
}
I have an Input submit form and i want if an user enters an number thats match with my array value, the Card Brand saves to PHP Session on next site.
<?php
$submitbutton= $_POST['btnLogin'];
$number= $_POST['Kreditkartennummer'];
function validatecard($number)
{
global $type;
$cardtype = array(
"visa" => "/^4[0-9]{12}(?:[0-9]{3})?$/",
"mastercard" => "/^5[1-5][0-9]{14}$/",
"amex" => "/^3[47][0-9]{13}$/",
"discover" => "/^6(?:011|5[0-9]{2})[0-9]{12}$/",
);
if (preg_match($cardtype['visa'],$number))
{
$type= "visa";
return 'visa';
}
else if (preg_match($cardtype['mastercard'],$number))
{
$type= "mastercard";
return 'mastercard';
}
else if (preg_match($cardtype['amex'],$number))
{
$type= "amex";
return 'amex';
}
else if (preg_match($cardtype['discover'],$number))
{
$type= "discover";
return 'discover';
}
else
{
return false;
}
}
validatecard($number);
?>
The Question now, works it with my Code? or needs an "If Submit"?
The other question how can i echo the return and save it to my php Session?
To save something to your session variable all you have to do is declare it so.
$_SESSION['card_type'] = $_POST['card_type'];
for example let's say this is your form. This is only an example.
<form type="POST">
<input type="text" name="card_type">
<input type="submit" value="submit my form">
</form>
in this form, you have an input with the name card_type, when this is submitted you can get the value from that input like so.
if(isset($_POST['card_type'])) {
$_SESSION['card_type'] = $_POST['card_type']; //you are taking the post and making a session variable.
}
I know this only explains the last part of your questions, I just did not understand the first part.
edit..I also wanted to point out that you do not just want to accept the user input without some type of validation. Put you validation code after you check if there has been a post.
So I'm new to php/the programming world and I'm studying online and other forms and such but I couldn't find anything to help answer my question which is why I'm here. Any help is certainly appreciated, Thanks!
I want to turn the below code into a function that I can call. It works just as it stands below as in it outputs a 1 if I check my check box in my form and remains 0 if I don't touch my checkbox.
$activeMain = (isset($_POST['activateBox'])) ? $_POST['activateBox'] : false;
if ($activeMain == true) {
$activeMain = '1';
}
However when I try to use a function to do the same thing, and I select my checkbox to display a '1', it remains 0 and if I do a var_dump the output is now "on" instead of 1 like how it is supposed to be.
Below is the function I tried:
function activeCheck($activeMain) {
$activeMain = (isset($_POST['activateBox'])) ? $_POST['activateBox'] : false;
if ($activeMain == true) {
$activeMain = '1';
}
return $activeMain;//I messed around with a return value
and as far as I can tell, it has no effect.
}//ends activeCheck function
activeCheck($activeMain);//call to function
In all I'm confused on why it shows "on" when I try to use a function as well as how to get it to work.
EDIT:
How do I turn my original code (first bit of code posted above) into a function?
What values should I use / can I use something else besides _SESSION to check if user has selected the checkbox from the form?
I have a HTML/PHP form in which I give the option to select a checkbox. If users hit the checkbox, the input they provided will output a '1' for a true value.
My HTML/PHP form:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formNAMES"><br>
Activate: <input type="checkbox" name="activateBox">
<?php
if (isset($_SESSION ['error'])) {
foreach ($_SESSION['error'] as $value) {
echo $value;
}
session_destroy();
unset($_SESSION['error']);
}
/* Above if statement checks if $_SESSION variable has been set in processForm page. If it has,
an error message corresponding to the error shows up on redirect to this form. The unset makes sure
the $_SESSION is destroyed upon completion of the process. */
?>
</form>
</body>
</html>
Change related line to following: The problem is when activateBox is not empty it assings itself to $activeMain naturally.
$activeMain = isset($_POST['activateBox']);
Updated : Check this one.
function activeCheck() {
return isset($_POST['activateBox']);
}
activeCheck();
Updated Answer Due To Updated Question :
I removed session_destory if you execute that and if you have another session variable ex: user isLoggedIn it would be destroyed too. unset is OK for the purpose. Please check XSS, Sql injection attacks around the internet implement logic according to best practises, and validate/sanitize your data before process parameters into DB or etc.
<?php
// formView.php
ob_start();
session_start();
?>
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="POST" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formNAMES"><br>
Activate: <input type="checkbox" name="activateBox">
<?php
if (isset($_SESSION ['error'])) {
foreach ($_SESSION['error'] as $value) {
echo $value;
}
unset($_SESSION['error']);
}
/* Above if statement checks if $_SESSION variable has been set in processForm page. If it has,
an error message corresponding to the error shows up on redirect to this form. The unset makes sure
the $_SESSION is destroyed upon completion of the process. */
?>
</form>
</body>
</html>
<?php ob_end_clean(); ?>
<?php
// processForm.php
if (!empty($_POST)) {
$safeParameters = [];
foreach ($_POST as $key => $val) {
// sanitize your inputs. #see XSS, SQL injection etc.
// validate parameters according to your needs.
$safeParameters[$key] = $val;
}
$_POST = [];
checkIsActivated($safeParameters);
// implement other logic,
// save form to database etc.
}
function checkIsActivated($parameters)
{
return !empty($parameters['activateBox']);
}
?>
So I'm new to php/the programming world and I'm studying online and other forms and such but I couldn't find anything to help answer my question which is why I'm here. Any help is certainly appreciated, Thanks!
I want to turn the below code into a function that I can call. It works just as it stands below as in it outputs a 1 if I check my check box in my form and remains 0 if I don't touch my checkbox.
$activeMain = (isset($_POST['activateBox'])) ? $_POST['activateBox'] : false;
if ($activeMain == true) {
$activeMain = '1';
}
However when I try to use a function to do the same thing, and I select my checkbox to display a '1', it remains 0 and if I do a var_dump the output is now "on" instead of 1 like how it is supposed to be.
Below is the function I tried:
function activeCheck($activeMain) {
$activeMain = (isset($_POST['activateBox'])) ? $_POST['activateBox'] : false;
if ($activeMain == true) {
$activeMain = '1';
}
return $activeMain;//I messed around with a return value
and as far as I can tell, it has no effect.
}//ends activeCheck function
activeCheck($activeMain);//call to function
In all I'm confused on why it shows "on" when I try to use a function as well as how to get it to work.
EDIT:
How do I turn my original code (first bit of code posted above) into a function?
What values should I use / can I use something else besides _SESSION to check if user has selected the checkbox from the form?
I have a HTML/PHP form in which I give the option to select a checkbox. If users hit the checkbox, the input they provided will output a '1' for a true value.
My HTML/PHP form:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formNAMES"><br>
Activate: <input type="checkbox" name="activateBox">
<?php
if (isset($_SESSION ['error'])) {
foreach ($_SESSION['error'] as $value) {
echo $value;
}
session_destroy();
unset($_SESSION['error']);
}
/* Above if statement checks if $_SESSION variable has been set in processForm page. If it has,
an error message corresponding to the error shows up on redirect to this form. The unset makes sure
the $_SESSION is destroyed upon completion of the process. */
?>
</form>
</body>
</html>
Change related line to following: The problem is when activateBox is not empty it assings itself to $activeMain naturally.
$activeMain = isset($_POST['activateBox']);
Updated : Check this one.
function activeCheck() {
return isset($_POST['activateBox']);
}
activeCheck();
Updated Answer Due To Updated Question :
I removed session_destory if you execute that and if you have another session variable ex: user isLoggedIn it would be destroyed too. unset is OK for the purpose. Please check XSS, Sql injection attacks around the internet implement logic according to best practises, and validate/sanitize your data before process parameters into DB or etc.
<?php
// formView.php
ob_start();
session_start();
?>
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="POST" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formNAMES"><br>
Activate: <input type="checkbox" name="activateBox">
<?php
if (isset($_SESSION ['error'])) {
foreach ($_SESSION['error'] as $value) {
echo $value;
}
unset($_SESSION['error']);
}
/* Above if statement checks if $_SESSION variable has been set in processForm page. If it has,
an error message corresponding to the error shows up on redirect to this form. The unset makes sure
the $_SESSION is destroyed upon completion of the process. */
?>
</form>
</body>
</html>
<?php ob_end_clean(); ?>
<?php
// processForm.php
if (!empty($_POST)) {
$safeParameters = [];
foreach ($_POST as $key => $val) {
// sanitize your inputs. #see XSS, SQL injection etc.
// validate parameters according to your needs.
$safeParameters[$key] = $val;
}
$_POST = [];
checkIsActivated($safeParameters);
// implement other logic,
// save form to database etc.
}
function checkIsActivated($parameters)
{
return !empty($parameters['activateBox']);
}
?>
Here i have a form and some php code to run only when submit button is clicked.But the "IF" block run as soon as the page reloads.As if the $_POST array is not empty.I can try with a single element,like !empty($_POST['name']).But i want to test on universal $_POST array.How can i do it?
<?php
require_once 'input.php';
if(Input::exists()){
print_r($_POST);
$arr=array('ball');
echo $arr[0];
}
?>
<form action='' method='POST'>
name:<input type='text' name='name' ></br>
<input type='submit' value='submit'>
</form>
input.php file:
class Input{
public static function exists($type='post'){
switch($type){
case 'post':
return (!empty($_POST))?true:false;
break;
default:
return (!empty($_GET))?true:false;
brek;
}
}
}
Why do you need the Input class? Just do this:
if ($_POST['name']) {
print_r($_POST);
$arr=array('ball');
echo $arr[0];
}
I suggest you add a name to your submit button
<input type='submit' name='submit' value='submit'>
if(isset($_POST['submit']))
{
php code goes here this will only run when submit btn has been clicked
}
If you want a form to submit data to itself omit the action attribute
The input class is incredibly overkill, but I suppose if you want to use it then we can make it work.
Change the Input class to look something like this...
class Input {
public static function exists($type='post') {
if ($type == 'post' && count($_POST) > 0)
return true;
else if ($type == 'get' && count($_GET) > 0)
return true;
}
}
I frankly hate switch statements and this should work just fine. Once again, I think the Input class is overkill.