make a if statement run only when submit button is clicked - php

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.

Related

PHP Session Variable Array

Hi I'm trying to understand session variables, in particular using them with arrays. In the example code below, the user enters a letter and I want to add that submission to a session variable so that the next time the user submits a letter I don't lose the previous entry.
So if the user enters 'e' the array displays 'e', and if the user then picks 's' then the array will now display 'e' and 's'. This is my first experiment with PHP and sessions are proving a little difficult to wrap my head around. Can anyone help me understand how to go about getting the result I want, or where I have gone wrong in the code below? Many thanks in advance.
<?php
session_start();
function example()
{
$_SESSION['lettersGuessed'] = array();
$userLetter = $_GET['input'];
array_push($_SESSION['lettersGuessed'],$userLetter);
print_r($_SESSION['lettersGuessed']);
}
if (strlen($_GET['input'])==1) {
if (ctype_lower($_GET['input']))
{
echo "The user-submitted letter is lowercase.<br>";
example();
}
else
{
echo "Invalid submission<br>";
}
}
?>
<form action="" method="get">
<input name="input" value="Enter a letter!" />
<input type="submit" value="Submit" />
</form>
try it out without array_push in a more simple way
There is a simple change in example function.
Following is complete code
<?php
session_start();
function example() {
$userLetter = $_GET['input'];
$_SESSION['lettersGuessed'][] = $userLetter;
print_r($_SESSION['lettersGuessed']);
}
if (strlen($_GET['input']) == 1) {
if (ctype_lower($_GET['input'])) {
echo "The user-submitted letter is lowercase.<br>";
example();
} else {
echo "Invalid submission<br>";
}
}
?>
<form action="" method="get">
<input name="input" value="Enter a letter!" />
<input type="submit" value="Submit" />
</form>
?>
The problem is that your line in the beginning of example() resets the session variable to a blank array every time the function is called.
Update your example() function as follows:
function example()
{
$_SESSION['lettersGuessed'][] = $_GET['input'];
print_r($_SESSION['lettersGuessed']);
}
Thankfully, PHP is loosely-typed, so you don't have to manually define lettersGuessed as an array. Simply using [] afterwards will cause it to be handled as an array, and then using the = assignment operator will push $_GET['input'] into it.

PHP Button to carry out query and refresh page

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
}

how to call a PHP function from a form button

I have a form in my index.html that looks like this:
<form name="form" method="post" action="send.php">
.
.
.
.
Inside my send.php I have to functions, function generatekey () and function postData(), how call I call the postData() function from my action attribute in my form?
you can also make your action like this:
<form name="form" method="post" action="send.php?postData">
and in your send.php you can do this:
if(isset($_GET['postData'])){
postData();
}
Add a unique hidden field in your form like:
<input type="hidden" name="action" value="postData" />
send.php
<?php
function generatekey () {
// action
}
function postData() {
// action
}
if ( $_POST[ 'action' ] == 'postData' ) {
postData();
}
?>
Or read your submit value, if it's unique.
Basically there is no "easy" way to do that, you need to write some code in your script that will decide what function to call and when, like:
if($_POST['submit'){
postData();
}
Another option is to use one of the many MVC framework out there like Codeigniter or laravel.

PHP MVC passing form values to controller and model

I'm trying to send POST values to the controller and then pass it to the model in PHP but I'm not sure how to go about doing this.
This part of the controller is to see if the user requests for a view like ?action=game. This works.
But I'm trying to modify it to allow $_POST to be sent to it and then to the model.
function __construct()
{
if(isset($_GET['action']) && $_GET['action']!="" )
{
$url_view = str_replace("action/","",$_GET['action']);
if(file_exists("views/" . $url_view . ".php" ))
{
$viewname = $url_view;
$this->get_view($viewname . ".php");
}
else
{
$this->get_view('error.php');
}
}
else
{
$this->get_view('home.php');
}
}
Here's what I got. In the registration form page, the action of the form is ?process=register but it doesn't work.
if(isset($_POST['process']) == 'register)
{
$this->get_view('register.php')
}
Get_view function determines what model to bind with the view
function get_view($view_name)
{
$method_name = str_replace(".php","",$view_name);
if(method_exists($this->model,$method_name))
{
$data = $this->model->$method_name();
} else {
$data = $this->model->no_model();
}
$this->load->view($view_name,$data);
}
Since the action of your form is ?process=register, then process is still in the $_GET superglobal. What you can do to make it use post is add a hidden input field containing process.
With this:
<form method="post" action="script.php?process=register">
The form is POST'ed to script.php?process=register so you have $_GET['process'], not $_POST['process'].
Try this instead:
<form method="post" action="script.php">
<input type="hidden" name="process" action="register" />
To have $_POST['process']. Alternatively, you could keep the "process" in the GET and switch your if statement to check $_GET instead of $_POST.

how to call different action methods of one controller from one form in kohana 3.0

I have one form with two buttons (add1,add2). So when I click on button add1, I want to call action_add1() and clicking button add2 calls action_add2(). Both functions are part of Controller_Welcome.
How can I achieve this?
class Controller_Welcome extends Controller
{
public function action_add1()
{
//some logic
}
public function action_add2()
{
//some logic
}
}
public function action_form()
{
$action = $this->request->query('action');
if ($action && method_exists($this, 'action_'.$action))
{
$action = 'action_'.$action;
return $this->$action();
}
}
No Javascript required, just send form data to welcome/form with action param as button name.
With JavaScript:
<input type="submit" name="add1" />
<input type="submit" name="add2" />
$('input:submit').click(function() {
$('#myForm').setAttribute('action', 'add_' + this.name);
$('#myForm').submit();
return false;
});
I'm not sure of the exact syntax, but the main idea is here.

Categories