I'd like to increment a variable on clicking a submit button with name="ticker".
$speed = 0;
if ( isset($_POST['ticker'])){
echo $speed++;
}
What I want is to be able to repeatedly click the button and see 1 added to total each time clicked. It seems to work once and then stays at "1". Why?
session_start();
if(!isset($_SESSION['speed'])) $_SESSION['speed'] = 0;
if(isset($_POST['ticker'])){ /* If there is already a value set */
$_SESSION['speed']++; /* Increment by 1 */
}
If you want to increment variable after clicking submit, you should store this value to $_SESSION['speed'] and after that increment it. In this case you set speed on value 0 and each time you click on the submit is incremented by one.
Related
I'm trying to get a session variable to alternate between 0 and 1 on each page load.
So first time page loads
$_SESSION['turn'] = 0;
Second time
$_SESSION['turn'] = 1;
Third time
`$_SESSION['turn'] = 0;`
and so on.
Then I can call that variable later in the page.
I can't work out how to do this. I've tried a simple IF function but can't get it to work.
First the session must be started on any page wishing to make use of the session array. session_start()
Next you have to remember that initially the session variable you are using will not exist the first time you attempt to use it
So
<?php
session_start();
if ( !isset($_SESSION['turn']) ) {
// does not exist yet, so create with 0
// you may want to initialize it to 1, thats up to you
$_SESSION['turn'] = 0;
} else {
$_SESSION['turn'] = $_SESSION['turn'] == 0 ? 1 : 0;
}
Try this where the page is loaded.
$_SESSION['turn']=1-$_SESSION['turn'];
code:
<?php
session_start();
echo $_SESSION['turn'];
$_SESSION['turn']=1-$_SESSION['turn'];
?>
Edit : RiggsFolly !isset() is correct. mine misses it and it will give errors in log. and the first value is not 0
I have a textbox and a button that puts whatever you just typed into a database, then I have this to display all those things, along with a delete button and a "top" button
<?php
$resultset2 = $db3->query('SELECT * FROM ask');
if($resultset2->num_rows != 0) {
while ($rows = $resultset2->fetch_assoc()) {
$question_enter = $rows['question'];
$id = $rows['id'];
echo "<form action='' method='post'><input type='hidden' value='".$id."'
name='the_id'><div><p>$question_enter<input type='submit' value='Delete'
name='deletedefaultnote'><input type='submit' value='Top' name='putontop'>
</p></div></form>";
}
} else {
echo 'no results.';
}
?>
I have the delete button working, but I can't figure out how to get the "top" button to put an element on the top of the list that's being displayed. How should I do this?
If it's relevant, say item1 and item2 are on the bottom of a long list, if I put item1 on top of the list, then put item2 on top, item2 would be on top and item1 would be second on the list. I don't want the elements to return to their original position if something else goes on top.
To store the new ordering into database you have to update all positions. One simple approach would be to use a "position" column like sym mentioned.
With an position-column beginning with 1 (0 is the "guardian") you could then
update the "new top" item and set the position to 0 (guardian) after that you would have to update ALL items/rows and set the position to old_position+1.
As you can see this approach is heavy on queries so I would recommend not to update the table every time you click on your "top" button and instead order the items on frontend with something like jQuery (what Kuya) said and after you're done re-ordering your list save it in one big request with the method explained above.
UPDATE: To update the rows in your database you can also use a single query when so following conditions are met:
column position starts at 1 and is NOT unique
the new top position item's position was set to 0
Then you can simply do UPDATE tablename SET position = position + 1. The database will then automatically increment all position values (and position 0, the guardian will be available again).
I'm using HTML, PHP, jQuery for my website.
I've a check box on my form as follows:
<input type="checkbox" name="check_status" id="check_status" value="1"> Status
I want the same check box for two different values. In short, after submission of the form if check box is checked I should get the value 1 in $_POST['check_status'] array and if the check box is unchecked at the time of submission of form I should get the value as 0 in $_POST['check_status'] array after form submission.
Now as per the above HTML code if check box is checked I'm getting value 1 and if the check box is unchecked then I'm getting blank value.
How should I resolve this issue to achieve the desired result?
You can add condition in php. Hope this will help.
if(isset($_POST['check_status'])) {
$status = $_POST['check_status'];
} else {
$status = 0;
}
echo $status;
you can use this
$status = 0;
if(isset($_POST['check_status'])) {
$status = 1;
}
echo $status;
In case you really need those values to be send as 1 and 0 to the server ( maybe you can't change the server-side code), you can add a hidden field with the same name as your checkbox, and then use JavaScript/jQuery to fill that hidden field, before you submit the form, with 1 or 0, for checkbox being checked, respectively unchecked. .
$("#hiddenField").val( $('#checkbox').is(':checked') ? 1 : 0 );
The title is so general mainly because I don't know what should be the appropriate title for it. Let me just explain the situation:
Say that I have two textboxes named LastName0 and FirstName0 and a button called addMore. When I click addMore, another two textboxes will be created through JavaScript. These textboxes will be named LastName1 and FirstName1. When I click the addMore button again, another two textboxes button will be created and named LastName2 and FirstName2 respectively. This will go on as long as the addMore button is clicked. Also, a button named deleteThis will be created alongside the textboxes. This simply deletes the created textboxes when clicked.
I also initialized a variable called counter. Every time the addMore button is clicked, the counter goes up by 1, and whenever the deleteThis button is clicked, the counter decreases by 1. The value of the counter is stored in a hidden input type.
When the user submits the form, I get the value of the counter and create a For loop to get all the values of the textboxes in the form. Here is the sample code:
//Suppose that the user decides to add 2 more textboxes. Now we have the following:
// LastName0 FirstName0
// LastName1 FirstName1
// LastName2 FirstName2
$ctr = $_POST['counter']; //the counter == 3
for ($x = 0; $x < $ctr; $ctr++)
{
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//This will get the values of LastName0,1,2 and FirstName0,1,2
//code to save to database…
}
On the code above, if the value of counter is equal to 3, then the values of textboxes LastName0,1,2 and FirstName0,1,2 will be saved. Now here is the problem: If the user decided to delete LastName1 and FirstName1, the For loop will not be able to iterate properly:
$ctr = $_POST['counter']; //the counter == 2
for ($x = 0; $x < $ctr; $ctr++)
{
//Only LastName0 and FirstName0 will be saved.
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
Someone told me to use the "push and pop" concept to solve this problem, but I am not really sure on how to apply it here. So if anyone can tell me how to apply it, it'll be grand.
Add your input text boxes with name as array ie, <input type="text" name="FirstName[]" />
In php you can fetch them as a array. ie,
foreach($_POST["FirstName"] as $k=>$val){
echo $val; // give you first name
echo $_POST["LastName"][$k]; // will give you last ame
}
In this case even if one set of field is removed in HTML will not affect the php code.
One solution would be to use the isset function like this:
$ctr = $_POST['counter'];
for ($x = 0; $x < $ctr; $ctr++)
{
isset($_POST["LastName$x"])?$lastname = $_POST["LastName$x"]:;
isset($_POST["FirstName$x"])?$firstname = $_POST["FirstName$x"]:;
}
If it is possible, instead of using LastNameN and FirstNameN names try using LastName[N] and FirstName[N], this way the result is an array and you can iterate through it with a foreach, meaning you will not need the counter and the index of the value will not be important:
foreach ($_POST["LastName"] as $i=>$lastname) {
if (!isset($_POST["FirstName"][$i])) {
// This should only happen if someone messes with the client side before posting
throw new Exception("Last name input does not have a related First name input");
}
$firstname = $_POST["FirstName"][$i];
}
If not, then you may have to use your $counter in a different way
$current = 0;
while ($counter) { // Stop only when i found all
if (isset($_POST["LastName$current"]) {
$counter--; // Found one
$lastname = $_POST["LastName$current"];
$firstname = $_POST["FirstName$current"];
}
$current++;
}
A better way to solve this would be to use arrays for Firstname and Lastname. Instead of calling them Lastname0 and Firstname0, then Lastname1 and Firstname1, call them all Lastname[] and Firstname[]. Give them ID's of Lastname0 and Firstname0 and so on for the delete function, but keep the names as arrays.
When the form is submitted use the following:
foreach($_POST['Lastname'] as $i => $lastname) {
$firstname = $_POST['Firstname'][$i]
//... code to save into the database here
}
Be warned though that in IE if you have an empty field it will not be submitted, so if Lastname0 has a value, but Firstname0 does not, then $_POST['Firstname'][0] will in fact contain the value of Firstname1 (assuming it has a value in it). To get around this you can use javascript to check if a field is empty when submitting the form, and if so put the word EMPTY in it.
Do not use counter if not required
A much easier way is to add array name when admore clicked.
Give a name like first_name[] in textbox
if you create form like that you can use foreach through $_POST['first_name']
try var_dump($_POST) in you php code to see how things goes on.
Inside your for loop, maybe you could try...
if ((isset($_POST["LastName$x"])) && (isset($_POST["FirstName$x"]))){
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
This will check if the variables exists before you try to do anything with them.
I have a Session which I am using to hold items in a form that are accumulated up by the user until the user wants to proceed to checkout. Its a bit like a Shopping cart where items can be added from the form.
Logical breakdown of code:
Page loads, session starts
If $_SESSION['set'] is not set then set it to TRUE.
Display rest of page and form.
User hits "Add another item" button.
Page data gets posted to itself
Page checks that $_SESSION['set'] = True and $_POST['add_item'] is set.
Page creates a session variables in an array, and adds posted values to those sessions.
Page increments $_SESSION['tariff_count'] if more needs to be added
The problem is that my code is not behaving as it should. When I click "Add new tariff" button the first time it does not get caught by my if function. This should be immediately caught. However when I go and press the button again, it finally works and adds an item to my session.
Here is the code:
//start a session to remember tariff items
session_start();
//testing the session array
print_r($_SESSION);
//destroy session if this character is found in URL string
$des = $_GET['d'];
if($des == 1)
{
session_destroy();
}
//checks to see if session data has been set
//if a session variable count is set then
if ($_SESSION['set'] == TRUE)
{
//perform a check to ensure the page has been called by the form button and not been accidently refreshed
if(isset($_POST['add_tariff']))
{
//if user clicks Add another tariff button then increase tariff count by one
//temp variable set to the current count of items added
$count = $_SESSION['tariff_count'];
$_SESSION['tariff_name'][$count] = $_POST['tariff_name'];
$_SESSION['tariff_net'][$count] = $_POST['tariff_net'];
$_SESSION['tariff_inclusive'][$count] = $_POST['tariff_inclusive'];
$_SESSION['tariff_length'][$count] = $_POST['tariff_length'];
$_SESSION['tariff_data'][$count] = $_POST['tariff_data'];
//increment tariff count if more data needs to be added to the sessions later.
$_SESSION['tariff_count']++;
}
}
//if no session data set then start new session data
else
{
echo "session set";
$_SESSION['set'] = TRUE;
$_SESSION['tariff_count'] = 0;
}
The code seems to be fudging my arrays of Sesssion data. All my added items in the session are displayed in a table.
However if my table shows six items, if i do a print_r of the session it only shows there are 4 items in the array? I have tested it to make sure I am not reprinting the same instances in the array.
Here is a print_r of the array that shows six rows but there are only four rows in this array?
[tariff_count] => 5 [tariff_name] => Array (
[0] => STREAM1TARIFF [1] => STREAM1TARIFF [2] => CSS [3] => CSS [4] => CSS
)
I have take a screenshot as well to show this strange problem
http://i.imgur.com/jRenU.png
Note I have echoed out "True Value =6" but in the print_r of the session it is only 5, so my code is missing out one instance (n-1).
Here is my code that prints all the instances in the session arrays, I have a feeling part of the problem in mismatch is caused by the "<=" comparison?
if(isset($_SESSION['tariff_count']))
{
for ($i = 0; $i <= $count; $i++)
{
echo "<tr>";
echo "<td>".$_SESSION['tariff_name'][$i]."</td>";
echo "<td>".$_SESSION['tariff_net'][$i]."</td>";
echo "<td>".$_SESSION['tariff_inclusive'][$i]."</td>";
echo "<td>".$_SESSION['tariff_length'][$i]."</td>";
echo "<td>".$_SESSION['tariff_data'][$i]."</td>";
echo "</tr>";
}
}
Paste bin of php page - http://pastebin.com/petkrEck
Any ideas, why my If statement is not catching the event when the user presses "Add another tariff" button the first time it is pressed, but then detects it afterwards?
Thanks for your time
Merry Christmas!
The problem is your code flow. In simplified pseudo-code, you're doing this:
if (session is not initialized) {
set = true
count = 0;
} else {
add posted data to session
}
On the first 'add item' call, the session is not set up, so you set up the session. AND THEN IGNORE THE POSTED DATA.
The code flow should be:
if (session is not initialized) {
set = true;
count = 0;
}
if (posting data) {
add data to session
}