Incrementing variable in php after action is processed? - php

Aim of my Program:
On my index.php file, an image is displayed.
I want that, when i user clicks that image, a new image should be displayed.
And when he clicks the new image, another new image should appear.
What have i done till now ?
<?php
$mycolor = array("red.jpg", "green.jpg", "blue.jpg");
$i = 0;
$cc = $mycolor[$i++];
?>
<form method="post" action="index2.php">
<input type="image" src="<?php echo $cc; ?>">
</form>
I know what the error is. Whenever, the page is reloaded, the variable $i is initialized to ZERO. How, do i fix that. How can I retain the incremented value after the image is clicked ?
Also, I have no Javascript Knowledge. So, if possible explain me in terms of php.

You have different possibilities to remember $i. e.g:
$_GET: http://php.net/manual/en/reserved.variables.get.php
Cookies: http://php.net/manual/en/function.setcookie.php
Sessions: http://php.net/manual/en/features.sessions.php
There is also no necessity to use a form for this problem. Just wrap the image with a hyperlink and modify the url by incrementing the parameter (index.php?i=1, index.php?i=2, index.php?i=3 and so on).

<?php
$mycolor = array("red.jpg", "green.jpg", "blue.jpg");
if (isset($_POST['i'])) { // Check if the form has been posted
$i = (int)$_POST['i'] + 1; // if so add 1 to it - also (see (int)) protect against code injection
} else {
$i = 0; // Otherwise set it to 0
}
$cc = $mycolor[$i]; // Self explanatory
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="image" src="<?php echo $cc; ?>">
<input type="hidden" name="i" value="<?php echo $i; ?>"> <!-- Here is where you set i for the post -->
</form>

You can either use sessions, cookies or a POST variable to keep track of the index, but some how you need to remember the last index so you can +1 it. Here's an example using another (hidden) post variable:
<?php
// list of possible colors
$mycolor = array('red.jpg', 'green.jpg', 'blue.jpg');
// if a previous index was supplied then use it and +1, otherwise
// start at 0.
$i = isset($_POST['i']) ? (int)$_POST['i'] + 1 : 0;
// reference the $mycolor using the index
// I used `% count($mycolor)` to avoid going beyond the array's
// capacity.
$cc = $mycolor[$i % count($mycolor)];
?>
<form method="POST" action="<?=$_SERVER['PHP_SELF'];?>">
<!-- Pass the current index back to the server on submit -->
<input type="hidden" name="id" value="<?=$i;?>" />
<!-- display current image -->
<input type="button" src="<?=$cc;?>" />
</form>

Related

Pass variable from one page to another, then discard it

Is there a way I can pass a variable from one page to another but it only work on the next page clicked? After that it can be discarded/destroyed.
I've tried a php session but can't seem to kill the session on the next page clicked... or even if that way may be the wrong way to approach it.
Here's my session code:
<?php
session_start();
$x = $category;
$_SESSION['sessionVar'] = $x;
echo "$x";
?>
<?php
session_start();
$x = $_SESSION['sessionVar'];
echo "$x";
?>
I want to do this without having to submit a form.
You can pass a variable via a php session and then unset the variable on the following page.
$_SESSION['my_var'] = "some data";
$_SESSION['my_var'] = null;
unset($_SESSION['my_var']);
Send it as POST:
<form action="nextpage.php" method="post">
<input type="hidden" name="yourvariable" value="12345" />
<input type="submit" name="submit" value="Next page" />
</form>
Is it what was supposed?

Add data to sql on button click

my page receives data which i retrieve with $_post. I display some data and at the bottom of page my button has to save data to mysql. I could submit form to next page, but how do i access the data that I have retrieved with post then? Lets say i have following code (in reality alot more variables ..):
<?php
$v= $_POST["something"];
echo $v;
echo "Is the following information correct? //this would be at the bottom of the page with the buttons
?>
<input type="button" value="submit data" name="addtosql">
You can do it in two methods:
1) You can save the POST variable in a hidden field.
<input type="hidden" name="somevalue" value="<?php if(isset($_POST["something"])) echo $_POST["something"];?>" >
The hidden value also will get passed to the action page on FORM submission. In that page you can access this value using
echo $_POST['somevalue'];
2) Use SESSION
You can store the value in SESSION and can access in any other page.
$v= $_POST["something"];
session_start();
$_SESSION['somevalue']=$v;
and in next page access SESSION variable using,
session_start();
if(isset($_SESSION['somevalue']))
echo $_SESSION['somevalue'];
Take a look. Below every thing should be on single php page
// first create a function
function getValue($key){
if(isset($_POST[$key]))
return $_POST[$key];
else
return "";
}
// process your form here
if(isset($_POST['first_name']){
// do your sql stuff here.
}
// now in html
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="first_name" value="<?php echo getValue("first_name"); ?>" />
<input type="submit" />
</form>

Button click counter [PHP]

I tried to create a variable to store a count of button clicked. Unfortunetlly i get this error:
Undefined variable: counter
It's my code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
And it's a form:
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = post>
<input type = "submit" name = "button" value = "Submit" >
<input type = "hidden" name = "counter" value = "<?php print $counter; ?>"; />
</form>
Anybody know what i'm doing wrong?
Alternatively, if you want to save the counter, you can use sessions. Like this:
session_start();
// if counter is not set, set to zero
if(!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 0;
}
// if button is pressed, increment counter
if(isset($_POST['button'])) {
++$_SESSION['counter'];
}
// reset counter
if(isset($_POST['reset'])) {
$_SESSION['counter'] = 0;
}
?>
<form method="POST">
<input type="hidden" name="counter" value="<?php echo $_SESSION['counter']; ?>" />
<input type="submit" name="button" value="Counter" />
<input type="submit" name="reset" value="Reset" />
<br/><?php echo $_SESSION['counter']; ?>
</form>
By the way, your current code will show an Undefined index error because you are echoing $counter on your form but you haven't initialized it yet. It will only exist, upon first form submission, not upon first normal load of the page.
There is no error in your code. Its working at my end. You need to check two points:
PHP code should be above on HTML, HTML code will come after PHP code. So that $counter variable will be initialized.
PHP and HTML code should be on same page.
As OP edited the question: So, the line $counter = isset($_POST['counter']) ? $_POST['counter'] : 0; should not be in if-block. To be sure, ** Make this line as a first line of PHP file. Then only $counter variable will be available for whole page.
Variable is not defined because of this u get this error.
To hide this error write this in top of page error_reporting(0).
Check this..how to defined variable?
you try to use a undelaired variable
<input type = "hidden" name = "counter" value = "<?php print $counter; ?>"; />
................................................................^
this var doesn't exists as the error says. guess you have a wrong setup of your code.
like the php is not on the same side or not above the html

Image upload script only works for latest <li></li> saved in DB

Below is a script to upload images and save them to the DB.
On one page of the website, there's a table and inside each <li></li>, there is an upload icon where users can add one image.
The issue is the image upload only works for the "highest" empty <li> on the table.
Here, "highest" means the latest <li> saved in the DB (table is sorted by TIME DESC).
For instance, if I want to upload an image to a random <li></li> on the page, once I select an image, nothing happens. But if I select the "highest" empty (empty = no image saved in DB) <li></li>, it works like a charm.
HTML:
<li id="entry<?php echo $recipe_id ?>">
<div class="addimage_icon" id="upload<?php echo $recipe_id; ?>">
<form id="upload_icon" action="upload_extra.php" method="POST"
enctype="multipart/form-data">
<input class="upload" id="file" type="file" style="display:none" />
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>"/>
<img class="upload_icon" src="/upload_icon.png">
</form>
</div>
</li>
JAVASCRIPT (upload gets triggered as soon as one image is chosen):
<script>
$('.upload_icon').click(function(){
$(this).parent().find('.upload').click();
});
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
</script>
PHP:
<?php
include "includes/connnect.php";
$id = $_SESSION['id'];
$recipe_id = mysql_real_escape_string($_POST['recipe_id']);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$recipe_id= $_POST['recipe_id'];
//get image attributes
$add = query("UPDATE cookbook SET recipe_pic = '".$location."' WHERE recipe_id =
'$recipe_id'");
header(Location:"home.php");
}
?>
What's going here ?
There are many, many problems with your question. First of all the HTML you've posted is invalid. I suspect that your Javascript code has a problem with such invalid HTML. However, the following code has not (for your HTML code duplicated once for demonstration purposes):
NodeList.prototype.forEach = Array.prototype.forEach;
document.querySelectorAll('input[type="file"]').forEach(function (file) {
var click = function() {
file.click();
};
var change = function() {
console.log('change:', file.value);
};
file.form.querySelector('img').addEventListener('click', click);
file.addEventListener('change', change);
});
http://jsfiddle.net/eBLL5/
All you need is to assign the correct listeners to the correct elements, as you can see, I do not use any ID values because they are duplicated.
I can use as well duplicate IDs in case you think this is not an argument, this is demonstrated in a related answer:
remove text from multiple spans having same id
I hope this helps you to get the feets again on the ground so that you can continue to validate the HTML and clean up a little bit.
It appears that your html form has
<input type="hidden" value="<?php echo $recipe_id; ?>"/>
However, the input field name attribute is not present so the post data stream will not have a definition for $_POST["recipe_id"] field. The undefined value is likely being interpreted by your script as 0 and so only the top or "highest" li image is updated.
If you alter the input field thus:
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>"/>
You may have better results...
Just change this part :
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
With :
$("#file").change(function(){$(this).parents("form").get(0).submit();})
In your HTML, you have:
<form id="upload_icon" action="upload_extra.php" method="POST"
enctype="multipart/form-data">
Then your Javascript mentions:
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
According to some specifications (HTML4, HTML5), there shouldn't be same IDs on multiple elements. So, when you use an iteration, avoid printing ids without appending something unique on them, like:
<form id="upload_icon<?php print $recipe_id; ?>"
action="upload_extra.php" method="POST" enctype="multipart/form-data">
Your Javascript can be turned into something like the following. (please mind that you need to call this function after the page is loaded)
function afterPageLoad() {
var buttons = document.getElementsByClassName("upload");
for (i = 0; i < buttons.length; i++) {
buttons[i].onchange = function() {
this.form.submit();
}
}
}
Now, if your PHP code has stopped working, we would need to see that, too, at the part you omitted by writing
//get image attributes
where the $location variable is initiated.
In JavaScript provided its submitting the form by finding the element by ID, As in the HTML code the IDs are repeating (not a standard method, IDS can't repeat but class can) so the browser will always submit the last (highest) form only, that's why when adding image to highest row its working and in between its not.
Please check this code out
<script>
$(document).ready(function()
{
id = '';
$('.upload_icon').click(function(){
id = $(this).attr('id');
$(this).parent().find('#file'+id).click();
});
$(".upload").change(function () {
$('#upload_icon'+id).submit();
});
});
</script>
<style>
.upload_icon {
cursor:pointer;
}
</style>
<ul>
<?php for($recipe_id=1;$recipe_id<10;$recipe_id++): ?>
<li id="entry<?php echo $recipe_id ?>">
<div class="addimage_icon" id="upload<?php echo $recipe_id; ?>">
<form action="upload.php" method="POST" enctype="multipart/form-data" id="upload_icon<?php echo $recipe_id; ?>">
<input class="upload" id="file<?php echo $recipe_id; ?>" type="file" name="image" style="display:none"/>
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>" />
<img class="upload_icon" src="https://cdn2.iconfinder.com/data/icons/picons-basic-2/57/basic2-036_cloud_upload-128.png" id="<?php echo $recipe_id; ?>">
</form>
</div>
</li>
<?php endfor; ?>
</li>
In the HTMl code I have provided have different IDs for each forms (used the $recipe_id as suffix), when ever click event on the upload icon is fired it will check which upload icon is clicked by its attribute Id and then the respective input type file value is changed by finding the element by Id (used the same $recipe_id as suffix here also). On input type change event also same logic is used to fire the respective form.

keep adding value in php

Initially,the $number = 0. After 1st time clicking Add button, the value becomes 10. When 2nd time clicking, the value is changed to 20. then 3rd time is 30, 4th time 40.
Below is my code, is there anyone know how to fix it? Thanks!
<?php
$number = 0;
if(isset($_POST['add'])){
$number = $number +10;
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<?php echo $number; ?>
<input type="submit" name="add" value="Add" />
</form>
</body>
</html>
<input type="hidden" value="<?php echo $number ?>" name="number" />
Now change the $_POST['add'] to $_POST['number']
And $number = $_POST['number'] + 10;
This is fundamental to how PHP works.
There is no 'state' in between requests. This means that everything will be forgotten for every request. So if you want to retain data, you have to store it somewhere.
A couple of options:
A database such as MySQL
A session
A cookie
A caching system such as APC
First of all, your PHP needs a little adjusting:
<?php
$number = ($_POST['add'] != '') ? 0 : $_POST['add'];
$number += 10;
?>
<html>
Then add a hidden input above the <input type="submit">, like so:
<input type="hidden" name="add" value="<?php echo $number; ?>">
Use the session variable to retain the value per page request. Simple variable values is destroyed once script finish execution. Session variable will keep the value.
Read more about session
or use the database.
You need to save the value somehow. Either you use a database, like MySql, or you could save the value in a session variable.

Categories