How do I make a value not reset each page reload? - php

I am trying to show people their profiles from my database using PHP.
But every time a button is clicked I want the person_id ($which_person) to go up by 1 so the next person's profile is shown. I don't know how to do that because every time I click a button the page reloads so the variable "which_person" gets reset to 1.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assets-putinhouse/css/style1.css" rel="stylesheet" type="text/css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Festive&display=swap" rel="stylesheet">
<title>Put people in a house</title>
</head>
<body>
<?php
include "db/connection.php";
$conn = create_connection();
$which_person = 1; //This resets to "1" every time the page reloads
$getSql = "select * from Person where person_id = 1;";
$data_labels = mysqli_query($conn, $getSql)->fetch_all(MYSQLI_ASSOC);
?>
<div class="pagesize">
<h1>Put people in a house</h1>
<img src="assets-putinhouse/images/create_account.png" alt="profilepic" class="image_person">
<?php
foreach($data_labels as $labels)
{
?>
<li class="labels" data-id="<?php echo $labels['person_id'];?>">
<?php echo $labels["firstname"] ?>
<br>
<br>
<?php echo $labels["secondname"] ?>
<br>
<br>
<?php echo $labels["gender"] ?>
<br>
<br>
<?php echo $labels["descriptie"] ?>
</li>
<?php
}
?>
<br>
<form method="GET">
<input type="submit" class="slytherin_button" value="Slytherin" name="slytherin_button_name">
<br>
<input type="button" class="gryffindor_button" value="Gryffindor" name="gryffindor_button_name">
<br>
<input type="button" class="hufflepuff_button" value="Hufflepuff" name="hufflepuff_button_name">
<br>
<input type="button" class="ravenclaw_button" value="Ravenclaw" name="ravenclaw_button_name">
<br>
<input type="button" class="nextperson_button" value="Go to next person">
<p class="text_firstname">Firstname: </p>
<p class="text_name">Name: </p>
<p class="text_gender">Gender: </p>
<p class="text_info">Info: </p>
<?php
if(isset($_GET['slytherin_button_name'])) {
onFunc($conn, $which_person);
}
if(isset($_GET['gryffindor_button_name'])) {
offFunc();
}
function onFunc($conn, $wich_person){
$sqlUpdate = "UPDATE Person SET slytherin = slytherin + 1 WHERE person_id like '$which_person';"; //this does the value "slytherin" of which_person go up by 1;
mysqli_query($conn, $sqlUpdate);
$wich_person = $wich_person + 1; //which person goes up by 1 so the next person will be shown but gets reset at the start
}
function offFunc(){
echo "Button is clicked";
}
?>
</div>
<script src="assets-putinhouse/js/script.js"></script>
</body>
</html>
ยดยดยด

(Untested) Instead of:
$wich_person = 1;
It seems you could do something like:
if (isset($_GET["id"]) {
$wich_person = (int)$_GET["id"] + 1;
}
else {
$wich_person = 1;
}
and then add the following to your form:
<form action="?<?php echo $wich_person ?>" method="GET">
...
</form>
And also, unless I'm mistaken it seems you've forgot to add </form> to your code.
In any event, this code should add the current ID to your URL every time you press submit, where then it gets increased by 1.
Edit: This is intended as a quick solution based on the code structure you provided, but upon reflection not sure if it's exactly what you're looking for. More robust solutions could be had, such as cookies or sessionStorage.

Related

Solving a mathematical question in PHP/HTML without Javascript

Im kind of new to programming (taking a course currently) and our task over the weekend is to build a website (really basic) where we have to solve a addition of 2 random numbers. I was able to create those random numbers, but what with is, to create something like a field the user (in this case me) has to fill out and "submit"; and then the website should show my own anwser and the correct one. The issue im facing in addition to that is, that when i create a submit function the website refreshes and those random numbers change each time.
My code looks like this (forgive me for using german terms):
<?php
$zufallszahl = rand(1,100) . "+";
$zufallszahl1= rand(1,100);
$solution= bcadd($zufallszahl,$zufallszahl1);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Homework Taschenrechner</title>
</head>
<body>
<h1>Additionen</h1>
<hr>
<h4>Addiere die folgenden Zahlen:</h4>
<p> <?php echo $zufallszahl; echo $zufallszahl1 ?> <p>
<form method="post">
<input type="number" name="Usereingabe" min="0" placeholder="Deine Antwort">
</form>
</body>
</html>
I would really appreciate a "simple" solution, I googled this issue already for an hour, but most solutions are just too complicated for me right now, and i end up not understanding what the code is about. So just to sum up, I would like to know how to create a submit field that doesnt refresh the website so the random numbers stay and a field that "checks" the answer and says its true/false.
Although, if you were allowed to use JS, it would be a lot simpler. However, since you wanted it in just PHP, the code below should work. Feel free to modify it as per your needs
<?php
if(!isset($_POST['zufallszahl']) && !isset($_POST['zufallszahl1'])) {
$zufallszahl = rand(1,100);
$zufallszahl1= rand(1,100);
// $solution= bcadd($zufallszahl,$zufallszahl1);
} else {
$zufallszahl = $_POST['zufallszahl'];
$zufallszahl1 = $_POST['zufallszahl1'];
$solution = bcadd($zufallszahl,$zufallszahl1);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Homework Taschenrechner</title>
</head>
<body>
<h1>Additionen</h1>
<hr>
<h4>Addiere die folgenden Zahlen:</h4>
<p> <?php echo $zufallszahl . " + "; echo $zufallszahl1 ?> <p>
<form method="post">
<input type="number" name="zufallszahl" value="<?php echo $zufallszahl; ?>" readonly />
<input type="number" name="zufallszahl1" value="<?php echo $zufallszahl1; ?>" readonly />
<input type="number" name="Usereingabe" min="0" placeholder="Deine Antwort" value="<?php echo $_POST['Usereingabe'] ?? ''; ?>">
<button>Check Answer </button>
<?php if(isset($_POST['Usereingabe'])){ ?>
<?php if($_POST['Usereingabe'] == $solution)
echo "Correct Answer";
else {
echo "Wrong Answer. Correct answer is $solution";
} ?>
<?php } ?>
</form>
</body>
</html>
NOTE
If you are using version below PHP 7, just use <?php echo isset($_POST['Usereingabe'])? $_POST['Usereingabe'] : ''; ?> in place of <?php echo $userSolution ?? ''; ?>
So you can keep them in a _SESSION variable and when they submit the answer you can check the _POST variable against the _SESSION one
<?php
if(isset($_POST['Usereingabe']))
{
if($_POST['Usereingabe'] == $_SESSION['sol']){
$check = "correct answer";
}
else
{ $check = "wrong answer"; }
}
else {
$zufallszahl = rand(1,100) . "+";
$zufallszahl1= rand(1,100);
$solution= bcadd($zufallszahl,$zufallszahl1);
$_SESSION['zufallszahl1']=$zufallszahl1;
$_SESSION['zufallszahl']=$zufallszahl;
$_SESSION['sol']=$solution;
}
// do anything else u want
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Homework Taschenrechner</title>
</head>
<body>
<h1>Additionen</h1>
<hr>
<h4>Addiere die folgenden Zahlen:</h4>
<?php if(isset($check)) { echo $check; } ?>
<p> <?php echo $_SESSION['zufallszahl']; echo $_SESSION['zufallszahl1']; ?> <p>
<form method="post" action="*your file.php*">
<input type="number" name="Usereingabe" min="0" placeholder="Deine Antwort">
<button type="submit">Submit!</button>
</form>
</body>
</html>
You could use two extra input tags in your form of type="hidden" that contain the random numbers in their value fields, and check if they are empty. If they are, generate new ones, otherwise keep the old ones.

Buttons that affect a function - PHP

Scenario:
I am trying to have a part of my page constently run a function, the function is then affected when the above buttons are clicked.
The buttons call functions that are within the main/constant function; master($selected).
Here is what i have tried.
index.php:
<? session_start();
require("inc.ini.php");
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta charset="utf-8">
<title>Buttons to funtions</title>
</head>
<body>
<main>
<header>
<form method="post" action="<?=$_SERVER['php_self']?>">
<button type="submit" name="change" value="insert, <?$selected = "func1";?>">Func 1</button>
<button type="submit" name="change" value="insert, <?$selected = "func2";?>">Func 2</button>
</form>
<!--
I want to press a button and when it is pressed it calls the function selected and gives it the value of which the button represents.
-->
</header>
<figure>
<?
if($_POST['change']){
echo $selected;
master($selected);
}
?>
</figure>
</main>
</body>
</html>
inc.ini.php:
<? session_start();
function master($selected){
if($selected == "func1"){
function func1(){
echo "func 1";
}
}
if($selected == "func2"){
function func2(){
echo "func 2";
}
}
}
?>
Another side question. do i need to do these if statements, can the $selector jump straight to the new function.
Php is a server side language, this means that a request needs to be sent to the server to make your code run.
Also when a form submits all of it's children are sent, so it is not possible to distinguish which has been clicked.
That being said:
<?php
session_start();
require("inc.ini.php");
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta charset="utf-8">
<title>Buttons to funtions</title>
</head>
<body>
<main>
<header>
<form method="post" action="<?=$_SERVER['php_self']?>">
<button type="submit" name="change" value="Func1">Func 1</button>
</form>
<form method="post" action="<?=$_SERVER['php_self']?>">
<button type="submit" name="change" value="Func2">Func 2</button>
</form>
</header>
<figure>
<?php
if (isset($_POST['change'])) {
echo $_POST['change'];
master($_POST['change']);
}
?>
</figure>
</main>
</body>
</html>
If you use 2 forms then you get different values for the same name.
Looking at your inc.ini.php file it seems you're defining functions based on which input has been entered. I would suggest not doing this but if your heart is set on it then okay.
Please add a comment to this post if you need more help.
Hope this helps.

passing id on href and submitting form on same page

I am making social project form and im trying to add reply ..the reply button is a link that sends user to reply.php page with post id saved in href...on the reply.php my form action is the same page but when i click button to submit form it doesnot get the id and refreshes page with post and display error undefined id need help..
here is my reply.php
<?php
require('session.php');
$id=$_GET['id'];
//echo $id;
$submit=#$_POST['submit'];
$reply=#$_POST['reply'];
if(isset($submit)){
$id=#$_GET['id'];
$sql=mysqli_query($con,"INSERT INTO REPLY (reply,Username,post_id) VALUES '$reply','$user_check','$id'");
$sql2=mysqli_query($con,"SELECT * FROM REPLY WHERE post_id= '$id'");
while($row=mysqli_fetch_array($sql2)){
echo $row['Username']."<br/>".$row['reply']."<br/>";
}
}
else "error in submission";
?>
<!DOCTYPE html>
<html>
<title>Studhelp</title>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="w3.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<?php
$sql=mysqli_query($con,"select * from posts where post_id='$id'");
while($row=mysqli_fetch_array($sql)){?>
<!-- Middle Column -->
<div class="w3-col m7">
<div class="w3-row-padding">
<div class="w3-col m12">
<div class="w3-card-2 w3-round w3-white">
<div class="w3-container w3-padding">
<h3 class="w3-opacity"><?php echo $row['Username'] ;?></h3>
<?php
echo $row['Posts']."<br/>".$row['date']."<br/>";
}
?>
</p>
</div>
</div>
</div>
</div>
<form action="reply.php" method="post">
<input type="text" name="reply" >
<input type="submit" name="submit" value="reply">
</form>
this is the anchor tag send id to reply.php
Reply
If I understand correct you need to be able to read your "id" variable after you post the form. To achieve this use $_REQUEST instead of $_GET, like this:
$id = $_REQUEST['id'];
And also pass the variable with your form, as a hidden field:
<form action="reply.php" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="reply" />
<input type="submit" name="submit" value="reply" />
</form>
You didn't check if the fom was submitted
Enclose other PHP code after session.php inside a conditional checker such as:
if ($_POST):
You can use form tags to create a form and put the id field as hidden.
GET requests shouldn't be use to modify data

A PHP quiz that calculate averages

I'm trying to make a quiz that will show the person who take it the average of the number of answer they got right. For example: if they have 2 right it would display 66%. Can someone please explain to me how I can do something like this.
<!DOCTYPE html>
<html>
<head>
<title>Question</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="background-color:lightblue">
<h1 style="text-align:center;color:white"> Answer these Questions</h1>
<div class="container" style="margin-top: 50px">
<?php
$numcorrect=0;
// If the submit button has been pressed
if(isset($_POST['submit']))
{
// Check answer
if($_POST['answer'] == 21)
{
$numcorrect= ($numcorrect + 1);
}
if($_POST['answer1'] == 46)
{
$numcorrect= ($numcorrect + 1);
}
if($_POST['answer2'] == 2468)
{
$numcorrect= ($numcorrect + 1);
}
$average=$numcorrect/count ($numcorrect);
echo "<h1>Your Average is {$_POST['$Average']}</h1>";
}
?>
<!-- Quiz Form -->
<form method="post" action="questionassign1.php">
<ol>
<div class="form-group">
<h3><li>How old am I ?</li></h3>
<input name="answer" type="text" class="form-control" />
<h3><li>How old is my Mom?</li></h3>
<input name="answer1" type="text" class="form-control" />
<h3><li>What is my favorite number?</li></h3>
<input name="answer2" type="text" class="form-control" />
</li>
</div>
</ol>
<input name="submit" type="submit" value="Check answer" class="btn btn-primary" />
</form>
</div>
</body>
</html>
Use this code:
<?php
$numcorrect = 0;
// If the submit button has been pressed
if (isset($_POST['submit'])) {
// Check answer
if ($_POST['answer'] == 21) { {
$numcorrect++;
}
if ($_POST['answer1'] == 46) {
$numcorrect++;
}
if ($_POST['answer2'] == 2468) {
$numcorrect++;
}
$average = ($numcorrect/3)*100;
echo "<h1>Your Average is $average %</h1>";
}
}
?>
:)
$average=$numcorrect/count ($numcorrect);
echo "<h1>Your Average is ".$average."%</h1>";
You already calculated the average, so put it in the string with the . string concat operator. Additional hint: Check your code, what happens if I don't know any answer?

submit button being created inside of submit button

I'm having a problem with a submit button in a form, when clicked it first reloads the current page, which creates a submit button inside of the original one before posting to the post page.
You can see the behavior example here:
http://tampary.com/pick_game.php?c_id=15&p_id=0&f_id=1&l_id=1
You can click back in your browser after clicking "start game" and you will see the nested controls. Using Chrome and Firefox, you get same results. Any ideas what could be causing this behavior? ideally, I just want the php page to be redirected to after the form submit to just load up cleanly. Any help would be greatly appreciated
The complete code is as follows:
<?php
require_once(dirname(__FILE__).'/grl-lib/db.php');
require_once(dirname(__FILE__).'/grl-lib/ui.php');
require_once(dirname(__FILE__).'/grl-lib/family.php');
require_once(dirname(__FILE__).'/grl-lib/location.php');
require_once(dirname(__FILE__).'/grl-lib/contact.php');
$ui = new x_ui;
$ui->set_ui(1);
if (!empty($_POST)){
$p_id = $_POST['p_id'];
$f_id = $_POST['f_id'];
$l_id = $_POST['l_id'];
$c_id = $_POST['c_id'];
}else{
$p_id = $_GET['p_id'];
$f_id = $_GET['f_id'];
$l_id = $_GET['l_id'];
$c_id = $_GET['c_id'];
}
?>
<!DOCTYPE HTML>
<html lang="<?php echo $ui->getLocale($ui->language_id,1); ?>">
<head>
<?php include_once('grl-lib/gen_include.php'); ?>
<meta name="robots" content="noindex"> <!-- no indexing this page -->
<link href="css/main.css" rel="stylesheet" type="text/css">
<link href="css/devices.css" rel="stylesheet" type="text/css">
<title>Tampary<?php ' '._('game'); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name=viewport content="width=device-width, initial-scale=1">
</head>
<body class="color_bg">
<?php include('standard/header.txt'); ?>
<!-- all content -->
<div class="entire_content_length aling_text_c">
<div class="max_width_responsive align_container_c spc_a_5">
<div class="align_container_c spc_a_5 container_c">
<form id="pick_game" action="game.php" method="post">
<?php
$html = '<input type="hidden" name="p_id" id="p_id" value="'.$p_id.'"><input type="hidden" name="f_id" id="f_id" value="'.$f_id.'"><input type="hidden" name="l_id" id="l_id" value="'.$l_id.'"><input type="hidden" name="c_id" id="c_id" value="'.$c_id.'">';
//$html = $html.'<input type="submit" value="'._('Start Game').'">';
echo $html;
?>
<input type="submit" value="Start Game">
</form>
</div>
</div>
</div>
<?php include('standard/footer.txt'); ?>
</body>
</html>
I see you are using an Ajax script, which is fine. But is definitely the culprit cause I can see it responding the entire page in firebug.
I will bet you that your front page is Ajax to and you append something somewhere (can't find it this fast).
Whatever the case, I'm not convinced that what ever your doing (loading an entire page through AJAX) is good practice.
Looking at your AJAX requests will solve your inception button problem

Categories