PHP variables stays the same after 1 click, probably an easy solution - php

I can work with PHP a bit and want to learn much more about it!
I am now simulating some kind of fight between 2 characters.
The thing is, I can only do 1 round, so when I click the Fight button it only does 1 round.
I can't seem to find out why the Hitpoints don't change when I click Fight again.
This is the code:
<body>
<?php
$Hitpoints1 = 30;
$Hitpoints2 = 30;
?>
<form name="frmFight" form action="" method="post">
<table width="700" border="0" align="left" cellpadding="0" cellspacing="0">
<tr>
<td align="center">Character 1</td>
<td align="center">Character 2</td>
</tr>
<tr>
<td align="center"><?php
if (isset($_POST['btnFight'])) {
$Damage1 += mt_rand(2,9); }
$Total1 = $Hitpoints1 - $Damage1;
echo $Total1; ?></td>
<td align="center"><?php
if (isset($_POST['btnFight'])) {
$Damage2 += mt_rand(2,9); }
$Total2 = $Hitpoints2 - $Damage2;
echo $Total2; ?></td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"> </td>
</tr>
</table>
<p><input name="btnFight" type="submit" value="Submit" /></p>
</form>
</body>

Try to put your variables in user session:
<?php
session_start();
if(!isset($_SESSION['hitpoints_1'])) {
$_SESSION['hitpoints_1'] = 30;
}
if(!isset($_SESSION['hitpoints_2'])) {
$_SESSION['hitpoints_2'] = 30;
}
$Hitpoints1 = $_SESSION['hitpoints_1'];
$Hitpoints2 = $_SESSION['hitpoints_2'];
?>
But you should think about more durable storage, like SQL or file.

You seem to have missed some important points of how PHP works.
Your script is executed from the start every time it is requested, and it is requested every time you press the button.
This means; their hitpoints are set to 30 every time you press the button, THEN the damage is subtracted.
To save variables between each request, you have to either save it on the server (look into sessions) or save it in a way that the HTML can send back as a part of the request (store it in hidden fields in the HTML).

You are not "saving" the value of the hitpoints after the form is submitted. When the page reloads, you need to look at the POST data and edit the value of $Hitpoints1 and $Hitpoints2
So when you submit the form you also need to send more POST data for the new hitpoints value.
So have
<input type="hidden" name="hitpoint1" value="$Total1" />
<input type="hidden" name="hitpoint2" value="$Total2" />
Then when the page loads look for these vars:
if (isset($_POST['hitpoint1']) {
$Hitpoints1 = $_POST['hitpoint1']
}
if (isset($_POST['hitpoint2']) {
$Hitpoints1 = $_POST['hitpoint2']
}

Submitting the page resets the data, so $hitpoints are 30 again and it subtracts whatever the random number you have pressed produced.
Use sessions.

Each time you submit a form (e.g. by clicking a button) a new PHP request is created. Data from one request does not automatically continue into the next request.
There are two approaches to this
Use a session to store data between requests. This approach is more secure, as the internal data is not provided to the front end (where it can be changed). This is probably the way you want to go, for now.
Put the data you want to continue into the form so that it posted back to the script to process when you submit the form. This approach is less secure (as the user can edit the data posted back) but is more scalable (because the server has no state).

You reset the hitpoints on lines 3&4 everytime you load the page. Instead of echoing the total, you should set the total in a input box, and pass the parameter back:
echo $Total1;
becomes
echo '<input type="text" value=".'$Total1'." name="hitpoints1" title="Total Hitpoints for 1">;
Then, read your $_POST variable at the beginning of the file:
if(isset($_POST['hitpoints1']){
$Hitpoints1=$_POST('hitpoints1');
} else {
$Hitpoints1=30;
}
Do the same for hitponts2.

Related

No data submitted from a form

I have created a simple HTML form containing just one field. When I press submit some PHP code that I have written gets called and outputs text that would include submitted data if everything was working. But no submitted text gets printed by the PHP. The form has been created on a Godaddy HTML page and the form is as follows:
<FORM BORDER="1" action="http://www.bestpro.com.au/wordpress/PHB_action.php"
method="post" enctype="application/x-www-form-urlencoded"
eenctype="multipart/form-data" name="PHBForm" accept-charset="ISO-8859-1"
ienctype="text/plain">
<TABLE>
<TR>
<TD>First name:</TD><TD><INPUT type="text" name="firstname" id="firstname"></TD>
<TD></TD><TD></TD>
<TD> </TD><TD> </TD>
</TR>
<TR>
<TD> </TD><TD> </TD>
<TD> </TD><TD></TD>
<TD> </TD><TD><input type="submit" value="Submit"></TD>
</TABLE>
</FORM>
The PHP code output starts as follows:
This is where we end up.
Using `$_POST["firstname"]` which outputs nothing.
Using `htmlspecialchars($_POST["firstname"])` which also outputs nothing.
Question:
The PHP output doesn't include the value that I entered into the field.
Can anyone see what I am doing incorrectly?
I see nothing wrong here, so I can only assume it is something wrong with how you output it on your PHB_action.php page.
You say that you're placing $_POST['firstname'] on your page, but have you actually made sure to echo or print it to the page?
You can do this like so:
echo $firstname = $_POST['firstname']; // notice the echo placed before
or
$firstname = $_POST['firstname'];
print("$firstname");
EDIT:
I've notice you have put your post data inside of single quotation marks when echoing out to your page.
You must concatenate on your data rather than putting them inside of single quotes when echoing, like so:
echo 'Using' . $_POST['firstname']; // notice the dot in between the string and the post data.
Either that, or you have not installed PHP correctly (or at all) onto your server.
Hope this helps
So, this is pretty straight forward and I have written it up and will explain each bit as i go.
The PHP you need for this is:
<?php
if (isset($_POST['send']))
{
$fname = $_POST['firstName'];
if (!empty($fname))
{
echo "hello $fname";
} else {
echo "Please supply your first name.";
}
}
?>
$_POST['send'] is the name of your submit button, this will be the trigger for your PHP to initiate and run through the rest of the code.
$fname = $_POST['firstName']
This is just where I prefer to store the $_POST as a variable in the event you are going to re use it again it saves time writing the entire thing.
if(!empty)
if the username isn't empty (!empty meaning not empty) then perform the echo of $fname. however if it comes back as empty it will echo the else echo "please supply...;
Now for the form.
<form action="" method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td><input type="submit" name="send"></td>
</tr>
</table>
</form>
Just a straight forward form with a blank action on mine (I prefer to keep the PHP within the same file however I normally relay it back to a Class within a different file.
Each form input (First Name / Submit) must have a name="" value otherwise the PHP cannot read it and run with it.
I hope this makes sense and isn't too puzzling :)
Your input field should be inside tag and method should be post. Like:
<html>
<body>
<Form method=post>
<input id=mytextfield name=mytextfield type=text />
<input type=submit value=Submit />
</Form>
</body>
</html>

Send "Button"-ID on Submit

I have an PHP page, which contains a form with some different input fields, e. g. day, month, year etc.. The form method is POST, only one non-editable field (The user ID) is sent via GET.
Of course, there is a "Submit"-Button, which triggers the form Action (PHP Script on Server).
The form tags contain a table with empty cells too. Now comes my question:
If the user clicks into one of the table cells, the form should be submitted, but additional to the regular form data the ID of the table cell should be transmitted too (If via POST or GET doesn't matter to me). How can I do that?
//Edit 2:
...
<form method="post" action="<?= DOMAIN?>/.../addUserTimetable.php?uid=<?= $user->getUserID() ?>">
<select id="day" name="day">
...
</select>
...
<input name="yearend" id="yearend" ...>
<button type="submit">...</button>
<table class="bordered">
<tr>
<th>Std.</th>
<th>Montag</th>
<th>Dienstag</th>
<th>Mittwoch</th>
<th>Donnerstag</th>
<th>Freitag</th>
</tr>
<?php
for($i=1; $i<13;$i++) {
echo "<tr>";
echo "<th>".$i. "</th>";
for($j=1;$j<6;$j++) {
echo "<td id='h".$i. "d".$j. "' onclick='???'></td>";
}
echo "</tr>";
}
?>
</table>
</form>
...
The server sided procession is fine, but I haven't got any ideas - even after two hours google - how I could transmit the cell id additionally.
That shouldn't be to hard. Have a look at the following example:
<form>
<input type="text" name="something">
<table>
<tr>
<td><input type="submit" name="cel1">
</tr>
<tr>
<td><input type="submit" name="cel2">
</tr>
<tr>
<td><input type="submit" name="cel13">
</tr>
</table>
<input type="submit" value="save">
</form>
By giving the submit buttons in the table cells a name attribute, that name will also be present as a key on the $_REQUEST. Go ahead and var_dump the $_REQUEST and you'll see you can find out in the backend which button got pushed by checking which key exists.
Note that POST / GET is completely irrelevant here, both will work just the same. And obviously you could apply some css to those buttons to make them transparent and lay them on top of the table cells, so they don't look like buttons, but just "capture" the user's click.
One last side note, are you sure you want to send the userID as a GET parameter? That would be very easy for someone with bad intentions to manipulate. Consider not sending the ID at all, but keeping it in the session on the server.

Input hidden doesn't work properly

I'm developing a simple PHP page, this is a small part of my code that doesn't work properly.
I want to use DB and print some products and for each product, I want to show a "buy" button.
If I press this button, a hidden input must be set with the product id(which later has to be sent to another page).
But, if I use var_dump to control(if my data was correct), I can see that the ID is wrong (I see that its always shown in the last)
<form id="products_list" method="post" action="step2.php">
<table>
<tr>
<td align="center">Immagine</td>
<td align="center">Nome prodotto</td>
<td align="center">Descrizione prodotto</td>
<td align="center">Prezzo unitario</td>
<td align="center">Taglie disponibili</td>
<td align="center">Colori disponibili</td>
<td align="center">Nickname disponibili</td>
</tr>
<?php
$product = mysqli_query($mysqli, "SELECT * FROM products");
while ($row = mysqli_fetch_array($product)) {
$id = $row[id_products];
print("
<tr>
<td align=\"center\">".$row[img_products]."</td>
<td align=\"center\">".$row[name_products]."</td>
<td align=\"center\">".$row[description_products]."</td>
<td align=\"center\">".$row[price_products]."</td>
<td align=\"center\">".$row[size_products]."</td>
<td align=\"center\">".$row[color_products]."</td>
<td align=\"center\">".$row[nick_products]."</td>
<input type=\"hidden\" name=\"id_products\" value=\"".$id."\"/>
<td><input type=\"submit\" name=\"buy\" value=\"Acquista\"/></td>
</tr>");
}
?>
</table>
</form>
You should open and close your form within the while-loop.
EDIT
A little bit more explanation why you should open and close from within the while loop:
If the while-loop is inside the form tags, that means the hidden field is outputted multiple times within the same form. Since they are all named the same, you're only retrieving one value after the submit (the value of the last hidden input).
If you open and close the form within the while-loop, each hidden input and button are in their own form. Which means, when that form gets submitted, you're only retrieving the value of that specific hidden field. :-)

HTML form acting as get instead of post

I'm pretty new to the whole PHP/HTML deal, and I've run into a problem that I don't know how to fix. It's a pretty simple form that lets you enter data into database. The PHP code is as following:
<?
include("../sqlcontext.php");
$foo = mysql_query("SELECT*FROM users WHERE checksum='".$_COOKIE['userCookie']."'");
if($_COOKIE['userCookie'] == '' || !mysql_num_rows($foo)){
echo 'Du er ikke logget ind :( log ind her';
}
else{
if($_POST['genreKnap']){
$nameGenre = $_POST['nameGenre'];
$textGenre = $_POST['textGenre'];
$succes = mysql_query("INSERT INTO genre VALUES('null','$nameGenre','$textGenre')");
if($succes){
echo 'Yay!';
}else {
echo 'Oh no';
}
}
?>
The form is as following:
<form name="form1" method="post" enctype="text/plain" action="">
<table>
<tr>
<td>Genre navn:</td>
<td><input type="text" name="nameGenre" id="nameGenre" style="width:100%; padding-right: 1px" /></td>
</tr>
<tr>
<td>Genre beskrivelse:</td>
<td><textarea name="textGenre" id="textGenre" style="width:100%; padding-right: 1px"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="genreKnap" id="genreKnap" value="Go!"/></td>
</tr>
</table>
</form>
Whenever I press the submit button, it seems as though it acts as if it was a get method and not a post.
Aha!!!
You are not posting the form correctly.
Set the
action=""
to
action="code.php"
Assuming your php page is called code.php. Just change it to the name/path of the php page and the form will send the data to your php code to process.
When you leave action="" to blank, it posts the data to itself (the same page). It is not acting as GET, it is still acting as POST, but posting to the wrong place. I think you worded the title of the question wrong.
What do you mean it is acting like get instead of post.
Can you not read $_POST variables in your PHP?
remove the 'enctype="text/plain"' in your form code.
enctype="text/plain"
Take that out. It is provided for debugging purposes only and doesn't generate anything that is sane to parse with a machine.
Valid form enctypes:
application/x-www-form-urlencoded: This is the default content type
multipart/form-data
The content type "application/x-www-form-urlencoded" is inefficient
for sending large quantities of binary data or text containing
non-ASCII characters. The content type "multipart/form-data" should be
used for submitting forms that contain files, non-ASCII data, and
binary data.
Source: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.3.4
You're all ignoring the primary question and focusing on irrelevent items.
First of all more than anything he's using a short php opener <? not <?php now not every web server accepts short openers first up check that.
Echo out your $_POST vars and see if they're returning the correct items
echo "POSTS BELOW<br />";
echo $_POST['nameGenre']."<br />";
echo $_POST['textGenre']."<br />";
echo "<br />GETS BELOW<br />";
echo $_GET['nameGenre']."<br />";
echo $_GET['textGenre']."<br />";
Put this block of code directly below your php opener see what data it returns.
Also this if($_POST['genreKnap']){ is generally a bad way of doing it as its user input the safest way is a hidden field <input type="hidden" name="action" id="action" value="dopost" /> and change your if clause to if($_POST['action']=="dopost && isset($_POST['action'])){
Also set your form action="" to the actual page name not blank
Give all that a try and if its still not working we'll try something different
If you are send normal data without any files by the form .
Then enctype is not always needed .
But even if you want to include it
The correct way is :
enctype="multipart/form-data"
Also give a url in the action method of the form : <form action='example.php'>
I hope it solves the problem .

While loop form to delete mysql_entry

I have this chunk of code, which is displayed on a user's journal page. They can add an entry and they have the option to delete an entry once it's on the page.
Ill show the code with some comments and then explain the problem.
// Figures out how many recent posts to display
$posts = $config_journalposts + 1;
if($noposts!=1) {
// Gets the data from the query
while(($row = mysql_fetch_array($journalquery)) && ($posts > 1)) {
// For each of the posts that were gathered, display the following:
echo '<table border="0" width="100%">
<tr>
<td colspan="2" style="vertical-align:bottom;">
// Display the title as a link to be used as a permalink
<p class="fontheader">'.$row['title'].'</p>
</td>
</tr>
<tr>
// Show the o-so-important content
<td width="100%" style="vertical-align:top;padding-left:10px;">
'.$row['content'].'
</td>
</tr>
<tr>
// Show the date
<td style="font-size:8pt;padding-top:10px;">'.$row['date_day'].'/'.$row['date_month'].'/'.$row['date_year'].'</td>';
// Checks if the current user is the owner of the journal or an admin
if($_SESSION['user']==$pageowner || $_SESSION['user_rank']=='Admin') {
echo '<td align="right">
// FOCUS POINT
<form method="POST" id="deljournal">
<input type=\'hidden\' name=\'delete_id\' value=\''.$row['id'].'\' />
// A delete button that executes a bit of Javascript
<button type="button" class="button" name="delete" value="Delete" onClick="delete_journal()" />Delete</button>
</form>
// END FOCUS POINT
</td>';
}
echo '</tr>
</table>
<hr>
';
$posts --;
}
Here is the Javascript that gets triggered on the button press
function delete_journal() {
var answer = confirm("Are you sure you want to delete this journal entry?")
if (answer){
// Submits the form
$("#deljournal").submit()
}
}
This javascript triggers the forum in the PHP code above which reloads the page and triggers this at the very top of the page, before the tag
if(($_POST['delete_id'])) {
// Gets the post ID from the hidden forum tag
$deleteid = addslashes(strip_tags($_POST['delete_id']));
// Deletes the row that has the ID of the hidden form
mysql_query("DELETE FROM `gamezoid_accounts`.`journal_$pageowner` WHERE `id`='$deleteid'");
}
Now, for the problem. In the while loop, this form gets repeated over and over. What happens is that upon pressing the delete button, it triggers the form that has the ID "deljournal". Since all of them have the ID "deljournal" it does the one at the top of the page. Trying to embed the post ID into the form ID breaks the code because the mysql_query doesn't know that the delete function has been triggered in the first place.
Any way around this?
Reason why I'm using Javascript as a trigger is for the confirmation popup in case anyone askes.
Anyways, thanks heaps for reading this far!
<input type=\'hidden\' name=\'delete_id[]\' value=\''.$row['id'].'\' />
then only u will get all the values as array when posted.
<input type=\'hidden\' name=\'delete_id[]\' value=\''.$row['id'].'\' />
then only u will get all the values as array when posted.
and on server side u should use
$delete_values= implode (',',$_POST['delete_id']);
Found a solution.
I have changed the form to be
<form method="POST" id="deljournal_'.$row['id'].'">
<input type=\'hidden\' name=\'delete_id\' value=\''.$row['id'].'\' />
</form>
<button type="button" class="button" name="delete" value="Delete" onClick="delete_journal_'.$row['id'].'()" />Delete</button>
by adding the journal entry ID into the ID of the form and the onClick function. The javascript is just below it outside the table cell and looks like:
<script type="text/javascript">
function delete_journal_'.$row['id'].'() {
var answer = confirm("Are you sure you want to delete this journal entry?")
if (answer){
$("#deljournal_'.$row['id'].'").submit()
}
}
</script>
where the entry ID has been added to the function name and form ID tag. By putting the Javascript into a while loop and not into an external file, it can be manipulated with the loop to have the same values.
It is a bit messy and will slightly increase load times + execution times but it was the quickest way that I could find.
Hope this helps anyone else who has been having a similar problem.

Categories