php code for button counter - php

Am trying to run a php code which counts button clicks. It increments to 1 and then it doesn't count. here is my code:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
?>
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = post>
<input type = "submit" name = "button" value = "vote" >
</form>
Am not a php expert so can anybody please tell me where am going wrong?
Thanks

Use this php:
<?php
if(isset($_POST["button"])){
$counter++;
echo counter;
}
?>
Also, use this for the opening <form> element
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Try this:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
?>
<form action = "<?php echo $_SERVER["PHP_SELF"]; ?>" method = post>
<input type = "hidden" name = "counter" value = "<?php echo $counter; ?>" />
<input type = "submit" name = "button" value = "vote" />
</form>

Store the count in a session. Note that this stores a separate count for each user. If you want one single count that is shared between all users then you'll need to store it in a database.
<?php
// Start the session
session_start();
// Make sure a session variable exists
if ( !isset($_SESSION['count']) ) {
$_SESSION['count'] = 0;
}
// Check to see if a vote has been submitted
$vote = isset($_POST['button']) ? $_POST['button'] : false;
if ( $vote ) {
// Increment the vote
$_SESSION['count']++;
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<input type="submit" name="button" value="Vote">
</form>

Related

Undefined Offset when looking through an array to display values

Hey I am new to PHP and I am trying to take values from the user that were put into a form for a game. Every time the user enters text and clicks submit it should add it to the array. Every time it will show at the bottom of the page all the guesses currently in a ordered list until the user gets the right answer and wins.
<?php
$count =0;
$guesses = array();
if(isset($_POST['submit']))
{
$count = $_POST['count'];
for($r =0; $r < $count; $r++)
{
$guesses[$r] = $_POST['word'];
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "<?php echo $tell; ?>"/>
<input type = "hidden" name = "count" value = "<?php $count +=1;?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
for($t=0; $t < $count; $t++)
{
?>
<li><?php echo $guesses[$t];?></li>
<?php
}
?>
</ol>
I keep getting a Undefined offset: 0. I did some reading and I know it has something to do with either me filling the array wrong or calling the index wrong. Hope you can help show me how to resolve this problem. Thank you.
The output would be similar to:
Your guesses:
1. blue
2. red
etc
Look if you don't want to use Session variable then you have to set the values enter by the user in the hidden input tag. Below is the code you might required to get your specific result:
<?php
$guesses="";
if(isset($_POST['submit']))
{
$guesses= $_POST['count']." ".$_POST['word'];
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "Word"/>
<input type = "hidden" name = "count" value = "<?php echo $guesses;?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
$count = explode(" ", $guesses);
foreach($count as $val)
{
if($val!= ''){
?>
<li><?php echo $val;?></li>
<?php
}
}
?>
</ol>
EDITED:
Problem was that you foremost did not echo the $count in your form, you simply incremented it. So the post variable would be empty. Also, increment it after you add to the array instead of in the post.
<?php
if( !isset( $count ) ){
$count =0;
}
$guesses = array();
if(isset($_POST['submit'])) {
$guesses[$count] = $_POST['word'];
$count++;
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "<?php echo $tell; ?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
for($t=0; $t < count( $guesses); $t++)
{
?>
<li><?php echo $guesses[$t];?></li>
<?php
}
?>
</ol>
Try this code:
<?php
$guesses = array();
if(isset($_POST['submit']))
{
if($_POST['guesses'] != '')
$guesses = explode('|', $_POST['guesses']);
if(trim($_POST['word']))
$guesses[] = trim($_POST['word']);
}
?>
<h3>Guess the word I'm thinking</h3>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="text" name= "word" value="" />
<input type="hidden" name="guesses" value="<?php echo count($guesses)? implode('|',$guesses):''; ?>" />
<input type="submit" name="submit" value="Make a Guess" />
</form>
<ol>
<?php foreach($guesses as $guess) { ?>
<li><?php echo $guess;?></li>
<?php } ?>
</ol>

how to save data on javascript form

I have those 2 function on JS :
<script>
function inc(elem)
{
elem.value++;
}
function dec(elem)
{
if(elem.value>1)
{
elem.value--;
}
}
</script>
And this form in html:
<form method="POST" action= "tameio.php" >
<input type="hidden" value="0" id="counter" name="counter">
<input type = "submit" value = "NextPage" name = "submit" onClick="inc(document.getElementById('counter')); ">
<input type = "submit" value = "PreviousPage" name = "submit" onClick="dec(document.getElementById('counter'));">
</form>
And here is the php :
<?php
if(isset($_POST['submit']))
{
echo $_POST['counter'];
if($_POST['submit'] == 'NextPage'){
...
}
}
?>
So the problem is that after i click NextPage button, 0 goes 1 but it is not stored in the form so it goes 0 again on html . If i reclick it it is going to send 1 again. Should I use ajax instead ?
There is no need to do any of that,
<form method="POST" action= "tameio.php" >
<input type="hidden" value="<?=$current_page?>" id="counter" name="counter">
<input type = "submit" value = "NextPage" name = "submit" onClick="inc(document.getElementById('counter')); ">
<input type = "submit" value = "PreviousPage" name = "submit" onClick="dec(document.getElementById('counter'));">
</form>
And in PHP:
<?php
if(isset($_POST['submit']))
{
if($_POST['submit'] == 'NextPage')
{
$current_page = $_POST['counter'] + 1;
} else {
$current_page = $_POST['counter'] - 1;
}
} else {
$current_page = 1;
}
// Fetch the page data based on the current page
...
?>>
But I would recommend you do this with a GET instead of a post.
Previous Page |
Next Page
And in PHP:
<?php
if(isset($_GET['page']) && $_GET['page'] > 0)
$current_page = (int) $_GET['page'];
else
$current_page = 1;
Try like this-
<script>
function inc(elem)
{
document.getElementById('counter').value = elem.value +1;
}
function dec(elem)
{
if(elem.value>1)
{
document.getElementById('counter').value = elem.value -1;
}
}
</script>

PHP variable returns a null value

I've created a textbox so when the admin types a name and clicks submit, it will shows a list of retrieved data from the database.
<form method="post" action="">
<?php
$teacherName = $_POST['teacherName'];
if ($_POST['submitted'] == 1) {
if($teacherName != ""){
$getName = mysql_query("SELECT name, user_id FROM members WHERE name = '$teacherName'");
$teacherdetails = mysql_fetch_array($getName);
$teachername = $teacherdetails['name'];
$teacher_id = $teacherdetails['user_id'];
if($teachername != ""){
print $teachername . "<br/>";
} else {
print "Give a valid name <br/>";
}
}
}
if ($teachername == ""){ ?>
Teacher name:<input type="text" size="20" name="teacherName"><input type="hidden" name="submitted" value="1"><br/>
<input type="submit" value="Submit" />
<?php $getModule = mysql_query("......");
while ($row2 = mysql_fetch_array($getModule)) { ?>
<input type="checkbox" name="modules[]" value="<?php print $row2["module_id"]?>"/> <?php print $row2["module_name"] . '<br/>'; } ?>
</div><br/> <?php } ?>
<input type="submit" value="Submit" />
</form>
Below I wrote this code (in the same script):
<?php
$modules = $_POST['modules'];
for($i = 0; $i < count($modules); $i++){
$module=mysql_query("INSERT INTO module (module_id,user_id) VALUES ('$modules[$i]','$teacher_id')");
}
?>
but for some reason when I call the variable "$teacher_id" (which is the value I retrieved before from the database. It works fine in the form) it returns nothing. It's null but I can't understand why.
Am I doing something wrong?
First off, put the PHP outside the form tags, at the top.
Secondly, the data you are receiving could be an array; with more than one result set;
do this just incase it it returned as that;
foreach($teacherdetails AS $teacher) {
//also set the values of the variables here
echo $teacher['name'];
echo $teacher['user_id'];
}
Regarding the last bit, is the $teacher_id successfully printing a result?
Also, where is the modules being input and posted from?

How to create isset($_POST['id'.$var]) within loops?

I am trying to create a page where there are several fields and users can comment on each one. To create these fields and text inputs, I am running a while loop with the following html within it:
<form name = "replyform" method = "post" action = "">
<input id = "replytext<? echo $replyID; ?>" value = "replytext<? echo $replyID; ?>" name = "replytext<? echo $replyID; ?>" type="text" class = "span5">
</form>
And then using the following code to call the 'wall_reply()' function, submitting the text values.
if (isset($_POST['replytext'.$replyID])) {
echo wall_reply();//5, $_POST['replytext'.$replyID]);
}
Something's a miss though. Any ideas what could be wrong here?
You have loop to create these form and input?
put the loop inside the form tag, so that only one form will be created with multiple inputs.
this seem to work correctly, use it as your guide ;)
<?php
$maxposts=7;
if (isset($_POST['submit'])){
function wall_reply($id,$text){
echo '<hr />updating id '.$id.' with '.$text;
}
var_dump($_POST);
for ($i=0;$i<$maxposts;$i++){
$replyID = $i;
if (isset($_POST['replytext'.$replyID])) {
wall_reply($i,$_POST['replytext'.$replyID]);//5, $_POST['replytext'.$replyID]);
} else {
echo 'not set';
}
}
}
?>
<form name = "replyform" method = "post" action = "">
<?php
$replyID = 5;
for ($i=0;$i<$maxposts;$i++):
$replyID = $i;
?>
<input id = "replytext<?php echo $replyID; ?>" value = "replytext<?php echo $replyID; ?>" name = "$
<?php endfor; ?>
<input type="submit" name="submit" value="go"/>
</form>

more than 1 form at one page

I've problem with multiple form at one page. At page index I include 4 forms
include('./poll_1a.php');
include('./poll_2a.php');
include('./poll_3a.php');
include('./poll_4a.php');
The form code at every poll page is the same. I include some unique markers ($poll_code) for every scripts but the effect is when I use one form - the sending variable are received in the others. But I would like to work each form individually.
The variable $poll_code is unique for every script -> 1 for poll_1, 2 for poll_2 etc.
The same situation is with $cookie_name
$cookie_name = "poll_cookie_".$poll_code;
than, as I see, cookies have different names.
$poll_code = "1"; // or 2, 3, 4
?>
<p>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" name="<?php echo $poll_code; ?>">
<input type="hidden" name="poll_cookie_<?php echo $poll_code; ?>" value="<?php echo $poll_code; ?>">
<table>
<?php
//print possible answers
for($i=0;$i<count($answers);$i++){
?><tr><td style="\text-allign: left;\"><input type="radio" name="vote_<?php echo $poll_code; ?>" value="<?php echo $i; ?>"> <?php echo $answers[$i]; ?></td></tr><?php
}
echo "</table>";
echo "<br>";
if ($_COOKIE["$cookie_name"] == $poll_code ) {
echo "<br> nie można głosować ponownie ...";
} else {
?>
<p><input type="submit" name="submit_<?php echo $poll_code; ?>" value="głosuj !" onClick="this.disabled = 'true';"></p>
<?php
}
?>
</form>
</p>
Q: how to make this forms to work individually at one page?
//------------------- EDIT
the receiving part of the script
$votes = file($file);
$total = 0;
$totale = 0;
$poll_cookie = 0;
if (isset($_POST["vote_$poll_code"]) && isset($_POST["poll_cookie_$poll_code"])) {
$vote = $_POST["vote_$poll_code"];
$poll_cookie = $_POST["poll_cookie_$poll_code"];
}
//submit vote
if(isset($vote)){
$votes[$vote] = $votes[$vote]+1;
}
//write votes
$handle = fopen($file,"w");
foreach($votes as $v){
$total += $v;
fputs($handle,chop($v)."\n");
}
fclose($handle);
Of course, the $file have the unique declaration too (at top of the script, under the $poll_code declaration).
$file = "poll_".$poll_code.".txt";
I think the issue might be that <?php echo $poll_code; ?> is outside the loop so maybe that it's always using the same value assigned to it, maybe put it inside the loop

Categories