If, else if, both giving the same answer - php

I've been having some problems with a bit of PHP running when a form is submitted.
I'm trying to have a variable be determined by which submit button is being pressed and grabbing the $_POST['name'] to carry out some SQL select. There are currently two submit buttons in my form, reading YES and NO.
The problem I'm having is that I keep getting the same answer from my query, but when I test in my database it works just fine. It seems to be something in my if/else statement.
<?php
require_once ("/includes/session.php");
require_once ("/includes/db_connection.php");
require_once ("/includes/functions.php");
require_once ("/includes/validation_functions.php");
if ($_POST['answer1']) {
$chosenAnswer = 1;
} else if ($_POST['answer2']) {
$chosenAnswer = 2;
}
$query = "SELECT questionFlow.NxtQ FROM ";
$query .= "questionFlow WHERE area = '{$_SESSION['probArea']}' ";
$query .= "AND ANSid = '{$chosenAnswer}' AND Qid = '{$_SESSION['x']}'";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
print_r($row["NxtQ"]);
}
?>
<form action="Assets/ajax/questions.php" id="ajax-questionset" method="post">
<br />
<br />
<?php echo($howmany); ?>
<br />
<br />
<div><?php echo($currentquestion); ?></div>
<span>
<button class="btn btn-hero" type="submit" name="answer1" value="1"/><?php echo($answer1); ?></button>
<button class="btn btn-hero" type="submit" name="answer2" value="2"><?php echo($answer2); ?></button>
</span>
</form>
As per Bug's suggestion below, I've added in the javascript and tested with an alert which is now giving me the right value, but it's messed up my ajax and it's now loading the php page rather than doing this 'blind' (for want of a better word)
Any suggestions?
function buttonB_clickHandler(event) {
document.getElementById('hiddenId').value = 2;
document.getElementById('ajax-questionset').submit();
}
Resolved this by taking out the javascript .submit and applying it to the buttons them self to read type="submit".
Thanks again for all your invaluable feedback guys, I love this site, great community!

Read my comment and try something like this:
<input id="buttonA" type="button" value="do something" onclick="buttonA_clickHandler(event);"/>
function buttonA_clickHandler(event) {
document.getElementById('hiddenId').value = whatever;
document.getElementById('theForm').submit();
}
repeat the code for the other button changing the name of function and other code.

Try adding {} to the else statement and adding isset
if(isset($_POST['answer1'])){
$chosenAnswer = 1;
}
else {
if (isset($_POST['answer2'])){
$chosenAnswer = 2;
}
}

Related

Passing a value from a button to PHP in order to output the correct content

Below is the code i've been trying to use to make a series of options, some are just 'continue' while others you choose between the options and it changes in which direction the story goes. The code as is is live at thecycle.ie but at the moment when you click 'continue' it changes , correctly to start, and you click it again and it goes back to the first entry.
Basically when you click i want it to store a value, and use that value to check along with $i, which goes up as you go through the game, which choice was made and output the correct values.
$i = 0;
$question = simplexml_load_file('xml/question.xml');
$opt1 = $question->entry[$i]->opt1;
$opt2 = $question->entry[$i]->opt2;
$story = simplexml_load_file('xml/story.xml');
$theSpeaker = $story->entry[$i]->speaker;
$theSpeech = $story->entry[$i]->speech;
echo'<form method="post" action="main.php">';
if($_POST['click']=='opt0' && $i==0)
{
$i = 1;
$theSpeaker = $story->entry[$i]->speaker;
$theSpeech = $story->entry[$i]->speech;
echo '<h2>'.$theSpeaker.'</h2>';
echo '<p>'.$theSpeech.'</p>';
echo '</div>
<div id="menu_about" class="menu_start">
<br>
<button type="submit" name="click" id="submit" value="opt1">'.$opt1.'</button>
</div>
</div>
</div>';
}
elseif($_POST['click']=='opt1' && $i==1)
{
$i = 2;
$theSpeaker = $story->entry[$i]->speaker;
$theSpeech = $story->entry[$i]->speech;
echo '<h2>'.$theSpeaker.'</h2>';
echo '<p>'.$theSpeech.'</p>';
echo '</div>
<div id="menu_about" class="menu_start">
<br>
<button type="submit" name="click" id="submit" value="opt2">'.$opt1.'</button>
</div>
</div>
</div>';
}
else
{
$i = 0;
$theSpeaker = $story->entry[$i]->speaker;
$theSpeech = $story->entry[$i]->speech;
echo '<h2>'.$theSpeaker.'</h2>';
echo '<p>'.$theSpeech.'</p>';
echo '</div>
<div id="menu_about" class="menu_start">
<br>
<button type="submit" name="click" id="submit" value="opt0">'.$opt1.'</button>
</div>
</div>
</div>';
}
In your script delete line 27, there are too many curly braces /THIS ONE/:
<script type="text/javascript">
$(document).ready(function() {
$("body").show();
$("body").css("display", "none");
$("body").fadeIn(1000);
//
$("#submit").click(function(event) {
event.preventDefault();
newLocation = this.href;
$("body").fadeOut(1000, newpage);
});
function newpage() {
window.location = newLocation;
} /*THIS ONE*/
});
</script>
Button behaviour varies browser-to-browser in what elements of the tag are submitted and available. Change your [button] to an [input]. That way you can be sure that name, value, etc.. is available.
$i = 0;
Value of $i will always be 0 when the script is encountered. so it goes to the else part.
use session to store value of $i, change that session variable and conditions according to session variables.
Hope this helps.
Why don't you just add a session or cookie? then every time when you need the 'continue' button to change its value, just pass it the session / cookie value
Session are like constants who are passed in the whole site as long as the tab is not closed. They can be modified and accessed from anywhere in the site.
Cookies are the same but are still stored until you clear them or their lifespan end

how to call php function from submit button?

my filename is contacts.php that have two submit buttons;i want that if insert button is pressed insert function is called and if select is pressed select is called.i have written following code:
//contacts.php
<?php
if(isset($_REQUEST['select']))
{
select();
}
else
{
insert();
}
?>
<html>
<body>
<form action="contacts.php">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select()
{
//do something
}
function insert()
{
//do something
}
?>
but it is not working .please help
<?php
if (isset($_REQUEST['insert'])) {
insert();
} elseif (isset($_REQUEST['select'])) {
select();
}
Your code is calling insert() even if no button is clicked, which will happen when the page is first displayed.
use post method because it is secure
//contacts.php
<?php
if(isset($_POST['select']))
{
select();
}
else
{
insert();
}
?>
<html>
<body>
<form action="contacts.php" method="post">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select()
{
//do something
}
function insert()
{
//do something
}
?>
If you are using return inside function to return the result , you have to use echo to print the result while calling function.
if(isset($_REQUEST['select']))
{
echo select();
}
elseif(isset($_REQUEST['insert']))
{
echo insert();
}
As has been described by several people (summarizing the previous comments), you have two options.
The first is to send the data via POST or GET to the server directly and reserve (refresh) the page based on whatever you do inside select() and insert().
While this is not the right place for a POST v GET discussion, convention is to use POST when sending data to the server. POST is slightly more secure because the information is not stored in the browser. Read more about the two here: http://www.w3schools.com/tags/ref_httpmethods.asp
The second option is to use AJAX to accomplish your task without refreshing the web page. In short, AJAX uses Javascript methods that you place on your page to communicate with your server, thus avoiding the need for the PHP on the server to actually change anything on the page (which would require a refresh). A code example of AJAX can be found here: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
<?php
$insert = $_POST['insert'];
$select = $_POST['select'];
if ($insert) {
insert();
}
if ($select) {
select();
}
else {
echo 'press any button...';
}
?>
<html>
<body>
<form action="contacts.php" method="post">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select() {
echo 'you pressed the [select] button';
exit;
}
function insert() {
echo 'you pressed the [insert] button';
exit;
}
?>

Getting value to POST

I wanted to get value by clicking button. But it isn't working. Here is my code:
players.php
(header)
<?php
kick_ban(#$_POST['submit']);
getMsg();
?>
(Form)
<form method="POST" action="?go=players">
<input type="submit" name="kick" class="btn btn-warning" type="button" value="Wyrzuć" />
<input type="submit" name="ban" class="btn btn-danger" type="button" value="Zbanuj" />
<?php $idgracza = $sValue['playerid'] ?>
</form>
functions_admin.php
function kick_ban($post) {
require_once "../inc/SampRcon.class.php";
$config = getData('../inc/config.php');
$port = $config['port'];
$adrip = $config['adresip'];
$query2 = new SampRcon(''.$adrip.'', $port, "Modding1");
if ($query2->connect()) {
if(isset($_POST['kick'])){
$query2->kick($idgracza);
$_SESSION['success'] = 'Gracz o id '.$idgracza.' został pomyślnie wyrzucony z serwera.';
}
if(isset($_POST['ban'])){
$query2->ban($idgracza);
$_SESSION['success'] = 'Gracz o id '.$idgracza.' został pomyślnie zablokowany.';
}
}
else
{
$_SESSION['error'] = 'Błąd';
}
$query2->close(); // Close the connection
One problem is this line:
kick_ban(#$_POST['submit']);
You are only sending the submit variable (which is actually undefined) to the function.
What you want is this:
kick_ban($_POST);
Now I'm not saying this is a good way to code but that will send the whole post array into your function so you can access all the variables.
Another issue is when you try to access things in the kick_ban function:
$_POST['kick']
and
$_POST['ban']
should be:
$post['kick']
and
$post['ban']
The reason is that once you pass them into the kick_ban function the name of the array becomes $post instead of $_POST.
You need a hidden input to add $idgracza to the form:
<input type='hidden' name='idgracza' value = '".$sValue['playerid']."'>
Then access it in your kick_ban function: $post['idgracza']

PHP $_POST strange behavior, only works 2nd time form is posted

I'm genuinely stuck on something VERY irritating. After a couple of hours of trying everything I know I've ended up here to see if anyone can help. Here's the general idea.
I want one certain page to be available with a password sent via a form. There is no user, and the password will not change. This should be easy, right!
I've got a form which submits with the method set to post, and the action set to $_SERVER['PHP_SELF']. The plan is, when the password variable I've pre-defined matches what is typed in the form, one set of content shows on the page, when it doesn't you get a different set of content (a form).
Here's what's weird. When looking at a print_r I see whatever I submit in the form in the array, but when I put the right password in the array fills, then empties quickly. I see this on the page reload. It completely empties itself. Even stranger, the 2nd time I do this, it works. What am I missing here? I'd love to know!
Many thanks, and Merry Christmas.
---- some code ----
The form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
Some PHP from the top of the file;
$pass = '12846565488374';
if($_POST['pass']){ $login = $_POST['pass']; } else { $login = 'empty'; }
if($login != $pass) { $show = 0; } elseif($login == $pass){ $show = 1; }
----- solved ------
Turns out this was a JS plugin reloading the page without me knowing.
Try:
if(isset($_POST['pass']) AND $_POST['pass'] == $pass) {
$show = 1;
} else {
$show = 0;
}
Copied from the comment below:
PHP can't update anything after the page is loaded from the server... You can only use refresh or JS/AJAX to change the content. It would be much easier if you uploaded the whole page somewhere.
Try:
<?PHP
if(isset($_POST['pass'])
{
$pass = '12846565488374';
($_POST['pass'] == $pass)? $show = 1 : $show = 0;
echo $show;
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
<?PHP
}
?>
<?php
if (isset($_POST['pass']))
{
if ($_POST['pass'] == $pass)
{
$show = 1;
echo $show;
}
else
{
$show = 0;
echo $show;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
perhaps something like this?
the purpose for the echo is to show when the correct password is entered, $show changes to 1 and when wrong, changed to 0
Edit:
Your Parameters Checking for $show
<?php
if (isset($show) AND $show === 1)
{
echo "The Variable Is Set To 1";
}
elseif (isset($show) AND $show === 0)
{
echo "The Variable Is Set To 0";
}
?>
This is tested and working with your code.
Thank you for your help everyone - as Matanya said, it was indeed a Javascript issue that was reloading the page. It's a music player and it was placed the "true" part of the IF statement. I don't understand why it has this effect, but at least I know. I thought the error would be in my PHP. Here's the player in question: SCM Music Player http://scmplayer.net
Thanks again.

Prevent PHP from running until POST

So I'm really really really new to PHP and MySQL (just started today!).
I have a page that updates a MySQL database based on results from a post.
The way I have it now, the PHP code is on the page, and it works, but the problem is that it goes through on page load as well, that is, before the POST happens.
Any way to prevent this?
Here's my code:
<?php
//do stuff
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_row($result);
while($row = mysql_fetch_row($result)) {
//do something
}
}
else {
//do something else
}
// free result set memory
mysql_free_result($result);
$first = 0;
?>
<br />
<br />
<div id="addName">
<h3 class="caps">Want to add yourself?</h3>
<div class="box">
<br /> <br />
<form id="form1" name="form1" method="post" action="#">
Email:
<label>
<input type="text" name="email" id="email" />
</label>
<label>
<input type="submit" name="submit" id="submit" value="Submit" />
</label>
</form>
</div>
</div>
</div>
See, problem is that it will run //do something else before the form is filled out. Any suggestions?
Thanks!
Better Condition
if(isset($_POST['submit']) && !empty($_POST) ){
// now do with your post data
}
this will prevent empty data to be posted
if(isset($_POST['submit'])){
// do things when post has been made
// e.g. insert the data into SQL
}
Take a read of this page. The above code will check to make sure the submit button has been pressed.
If you are hosting the HTML form on a different page you can put this at the top of your code on the PHP page. It will redirect the user to the HTML form file before any code is executed.
if (!$_POST['submit']) {
header("Location: ./form.html");
die();
}
However if you prefer to keep the form on the same page (which it looks like you are) you can use the suggestions above.

Categories