I want it to increment and decrement the value in $_SESSION['selection'].
Mousedown on next form results in: "The session is 1".
Mousedown on previous form results in "The session is -1".
Here is the code:
<?php
if (isset($_POST['next'])) {
displaynext();
}
else if (isset($_POST['previous'])) {
displayprevious();
}
else {
session_start();
echo "session started";
$_SESSION['selection'] = 1;
}
function displaynext() {
$_SESSION['selection'] = $_SESSION['selection'] + 1;
echo "The session is $_SESSION[selection]";
}
function displayprevious() {
if ($_SESSION['selection'] != 1) {
$_SESSION['selection'] = $_SESSION['selection'] - 1;
}
echo "The session is $_SESSION[selection]";
}
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="previous" value="Previous">
</form>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="next" value="Next">
</form>
Put the session_start() call on the beginning of your file; right after the <?php open tag. You also need to do that on every script that you plan to use sessions.
By the way, instead of writing:
$_SESSION['selection'] = $_SESSION['selection']-1;
$_SESSION['selection'] = $_SESSION['selection']+1;
You can use
$_SESSION['selection']--;
$_SESSION['selection']++;
Read: Increment/Decrement operators
Make sure you're using session_start() on every page you use your session on.
Put the session_start call to the beginning of your code, outside of any conditions.
session_start needs to be called in every script you're using the session in, not just at the very beginning (ie. the first pageload).
You're not calling session_start when moving between pages. Move the call to before the if statements, like this:
session_start();
if(isset($_POST['next'])) {
displaynext();
} else if(isset($_POST['previous'])) {
displayprevious();
} else {
echo "session started";
$_SESSION['selection'] = 1;
}
Related
We need to create a program that lets the user input the array size, their name, and age (depending on the array size the user entered). After that, we need to display all the elements of the array.
This is my code, but I'm having a problem adding a new element for another user and displaying it.
<html>
<head>
<title> PHP Array </title>
</head>
<body>
<form method="post" action="example.php">
<h3> Please enter the your information: </h3>
Array Size: <input type="text" name="arraysize"/> <br/><br>
Name: <input type="text" name="name" /><br/><br/>
Age: <input type="text" name="age"/> <br/><br/>
<input type="submit" name="submit" value="Submit"/>
<input type="reset" name="cancel" value="Cancel"/><br/><br/>
<?php
if(isset($_POST['submit'])){
if((!empty($_POST['name'])) && (!empty($_POST['age'])) && (!empty($_POST['arraysize']))){
$info = array($_POST['arraysize'], $_POST['name'], $_POST['g6ave']);
$arraylength = count($info);
for ($i=0; $i<=$arraylength ; $i++) {
$name = $_POST['name'];
for ($j=1; $j<=$i; $j++){
echo "User's Name" .$i. ": " .$name. [$j] ."<br>";
$age = $_POST['age'];
for($k=0; $k<=$i; $k++){
echo "User's Age: " .$age. [$k] ."<br/>";
}
}
}
}
}
?>
</body>
</html>
One approach (of other possible approaches) below should give you the main ideas. I also commented the aim of the each script part.
Approach below assumes that you'll use same URL for all your form pages. (1st, 2nd and the success page)
I hope this helps.
session_start(); //Start new or resume existing session
if (isset($_SESSION['form_success']) && $_SESSION['form_success'] === true)
{
require 'success_page.php';
unset($_SESSION['form_success']); // don't needed anymore
return; //not to continue to execute the code
}
// decide the page from user
if (isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
// display the first form page for the 1st time
require 'first_page_form.php';
return; //not to continue to execute the code
}
// if the first page was submitted.
if ($page === 'first') // or a specific POST flag from 1st page
{
//verify data from first page
$warnings = [];
if (first_page_data_valid() === true)
{
require 'second_page_form.php';
return; //not to continue to execute the code
}
// populate $warnings during first_page_data_valid()
//if first page data are invalid
print_r($warnings);
require 'first_page_form.php'; //display again
return; //not to continue to execute the code
}
// if the second page was submitted.
if ($page === 'second') // or a specific POST flag from 2nd page
{
//verify data from second page
$warnings = [];
if (second_page_data_valid() === true) // populate $warnings during second_page_data_valid()
{
// do things. ex: DB operations.
if (db_actions_success() === true)
{
$_SESSION['form_success'] = true; // defined and set to true.
// PHP permanent URL redirection. usage of 301 is important.
// it clears POST content. Prevents F5/refresh.
header("Location: https://www.url.com/form.php", true, 301);
exit; // good/recommended to use after redirect
}
else
{
echo 'System down or I have a bug. Try again later.';
return; //not to continue to execute the code
}
}
//if second page data is invalid
print_r($warnings);
require 'second_page_form.php'; //display again
return; //not to continue to execute the code
}
I'm trying to post array data to another php, but it doesn't work..
here is my code below.
in func.php
function search($x, $y)
{
...
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
echo"<form method=post action='map.php'>";
for($i = 0; $i < 8; $i++)
{
//echo $martx[$i]."<br/>";
//echo $marty[$i]."<br/>";
echo "<input type='hidden' name='martx[]' value='".$martx[$i]."'>";
echo "<input type='hidden' name='marty[]' value='".$marty[$i]."'>";
}
echo "</form>";
header("location: map.php?x=$x&y=$y");
}
martx and marty have data from parsed xml $load_string
And I want to post these data to map.php by form with POST. So, I expect that I can use two arrays martx and marty in map.php like $_POST[martx][0]..
But when I run this code, page remains in func.php, instead of redirecting to map.php
Am I make some mistake?
Thanks in advance.
========================================================================
Thank you all for your kind concern and helpful advice!
I edit my code with your advice,
I delete all echo with using javascript
And I add submit code
here is my code below
....
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
?>
<form method='post' action='map.php?x=<?=$x?>&y=<?=$y?>' id='market'>
<script language="javascript">
for(i = 0; i < 8; i++)
{
document.write('<input type="hidden" name="martx[]" value="<?=$martx[i]?>">');
document.write('<input type="hidden" name="marty[]" value="<?=$marty[i]?>">');
}
document.getElementById('market').submit();
</script>
</form>
<?php
//header("location: map.php?x=$x&y=$y");
}
With this code, page redirect to map.php successfully.
But I can't get data like $_POST['martx'][i] in map.php
I think document.write line cause problem
when I write code like
document.write('<input type="hidden" name="martx[]" value="$martx[i]">');
result of $_POST['martx'][i] is "$martx[i]"
Is any error in this code?
I want to use POST method but if I can't post data with POST,
then I'll use session-method as #Amit Ray and #weigreen suggested.
thanks again for your concern.
First, You try to use header('location: xxx') to redirect user to another page.
As the result, you are not submitting the form, so you won't get data like $_POST[martx][0] as you expect.
Maybe you should try using session.
I can see some errors that you are making when you are doing header redirect. There should be no output before you call header redirect but you are doing echo before redirect.
use session to tackle this issue
function search($x, $y)
{
...
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION["martx"] = $martx;
$_SESSION["marty"] = $marty;
header("location: map.php"); exit;
then in map.php you can retrieve the session variables
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$martx = $_SESSION["martx"];
$marty = $_SESSION["marty"];
Then you can use a for loop or foreach loop to iterate through the values
This is a simplified version of what I want to accomplish:
In my script I want a static variable x to be incremented every time the submit button is pressed.
<?php
function IncX(){
static $x = 0;
$x++;
echo $x;
}
?>
<body>
<form>
<input type="submit" name="submit" class="next btn btn-primary" value="Submit" />
</form>
</body>
But it initializes to x=0 on every page reload after submit.
You're loading the variable afresh every time the page loads, so it's always going to be the same.
The solution is to store it in a session and then increment it there. Include a conditional to create the variable if it doesn't already exist.
<?php
session_start();
if (!isset($_SESSION['x'])) {
$x = $_SESSION['x'];
} else {
$x = 0;
}
$x++;
echo $x;
$_SESSION['x'] = $x;
?>
<?php
session_start();
$x = 0;
if (isset($_SESSION['x'])) {
$x = $_SESSION['x'];
$x++;
} else {
$_SESSION['x'] = $x;
}
// /$x++;
echo $x;
$_SESSION['x'] = $x;
?>
Apache doesn't keep track of variables in php scrips between clicks, you would have to store it somewhere, be it the $_SESSION or a database.
Moreover, the static keyword doesn't do what you seem to think it does. It would work for successive calls of the function in a single run of the script, but not between clicks.
in any event, you can use the ternary operator to achieve this, would you happen to put it in the session. I've also added a check to make sure the variable is actually a viable count number:
session_start();
$_SESSION['x'] = isset($_SESSION['x']) && is_int($_SESSION['x'])
? $_SESSION['x'] + 1
: 1;
echo $_SESSION['x'];
Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.
Can i write some code to execute while my check box is checked in my php code..
my declaration of check box is...
<input id="checkbox" name="click" type="checkbox" onclick="check(this)"/>
i thought to perform a function called check() while clicking the check box..
<script type="text/javascript">
function check(cb)
{
if($("input[type=checkbox]:checked"")
{
//my functionality and operations
}
}
But its not working, how can i perform the onclick event in the Checkbox's action..
First of all, there's a mistake. It should be .is(":checked").
function check(cb)
{
if($(cb).is(":checked"))
{
//my functionality and operations
}
}
And the HTML should be:
<input type="checkbox" onclick="check(this);" />
Or, if you wanna invoke a PHP Function after clicking on Checkbox, you need to write an AJAX code. If this is the case, in your if condition, and checked condition, you can call a PHP file, that calls only this function.
function check(cb)
{
if($(cb).is(":checked"))
{
$.getScript("clickCheckbox.php");
}
}
And you can write JavaScript plus PHP in the clickCheckbox.php file, say something like this:
clickCheckbox.php
<?php
header("Content-type: text/javascript");
unlink("delete.png");
echo 'alert("Deleted!");';
?>
Once you click on the checkbox, and if the state is checked, it gives out an AJAX call to this PHP file, where you are deleting a file delete.png and in the echo statement, you are outputting a JavaScript alert, so that you will get an alert message saying Deleted!.
$('#myform :checkbox').click(function() {
var $this = $(this);
// $this will contain a reference to the checkbox
if ($this.is(':checked')) {
// the checkbox was checked
} else {
// the checkbox was unchecked
}
});
Where your form has id myform
use
if ($('#checkbox').is(':checked'))
or inside an event
$('#checkbox').click(function(){
if ($(this).is(':checked')){
//your routine here if checked
}else{
//routine here if not checked
}
});
You can put like this:
Include the column checked in your table with default value NO.
Then after your SELECT statement show the array.
page1.php
<input type=checkbox value="<?php $row['checked']?>" onclick="location.href = 'update.php?id=<?php echo $row['id']; ?>&checked=<?php if ($row['checked'] == 'YES') { ?>NO<?php } else {?>YES<?php } ?>';" <?php if ($row['checked'] == 'YES') { ?> checked <?php } ?>>
update.php
<?php include('server.php'); ?>
<?php
$id = $_GET['id'];
$checked = $_GET['checked'];
if(isset($_GET['id']))
{
$sql = "UPDATE table SET
checked = '$checked'
WHERE `id` = '$id' ";
if ($conn->query($sql) === TRUE)
{
}
else
{
echo "Error updating record: " . $conn->error;
}
header('location: page1.php');
}
?>
Try this one
<input id="checkbox" name="click" type="checkbox" onclick="check()"/>
//in js
if( $('input[name=checkbox]').is(':checked') ){
// your code
}