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.
Related
I am trying to make an inex.php file as a dashboard page that shows a selection of files that are part of the folder that index.php is part of. and when the user selects the file, I want it to redirect to that page. I am using xammp as a local webserver for this.
<!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">
<title>index</title>
</head>
<body>
<h1>Admin portal</h1>
<h3>select a php file relevent to a table in the database you would like to manage :index brings you right back :(</h3>
<form action="" method="POST">
<label for="pages">page:</label>
<select name="pages" id="page">
<?php
foreach (glob("*.php") as $filename) {
echo "<option value='strtolower($filename)'>$filename</option>";
}
?>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I am using a foreach to get all the files that are in the folder and populate them in a selection menu. I want to know how I can redirect to those files when I hit submit.
Your code is correct, you need only remove strtolower method from value, and use onchange on select tag.
Edit, Second Sol when submitted form :
<form action="" method="POST" onsubmit="return submitForm()">
<label for="pages">page:</label>
<select name="pages" id="page" >
<?php
foreach (glob("*.php") as $filename) {
$filename = strtolower($filename);
echo "<option value='$filename'>$filename</option>";
}
?>
</select>
<br><br>
<input type="submit" id='submitBtn' value="Submit">
</form>
<script type="text/javascript">
function submitForm(){
window.location.href = document.getElementById("page").value;
return false;
}
</script>
First sol,Try it:
<select name="pages" id="page" onchange=" (window.location = this.value);">
<?php
foreach (glob("*.php") as $filename) {
$filename = strtolower($filename);
echo "<option value='$filename'>$filename</option>";
}
?>
</select>
Don't use a select to redirect, use a <a> tag.
<!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">
<title>index</title>
</head>
<body>
<h1>Admin portal</h1>
<h3>select a php file relevent to a table in the database you would like to manage :index brings you right back :(</h3>
<h1>pages</h1>
<ul>
<?php
foreach (glob("*.php") as $filename) {
echo "<li>" . $filename . "</li>";
}
?>
</ul>
</body>
</html>
// edit: wrong concat operand
I'm trying to create a post request on the same page with infinite amount of posts. The only problem is that the post that I am doing keeps overwriting.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="https://wikiscams.org/form.php" method="post">
<input type="text" placeholder="Anon" name="user">
<input type="submit" name="submit">
</form>
</body>
</html>
<?php
if(isset ($_POST["submit"])) {
$user = $_POST['user'];
// echoes post but overwrites
echo $user;
}
?>
What should I do?
With HTML you can use arrays on PHP side and that's what you need right now.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<form action="https://wikiscams.org/form.php" method="post">
<?php if(!empty($_POST['user'])){
foreach ($_POST['user'] as $key => $value) { ?>
<input type="hidden" name="user[]" value="<?=$value?>">
<?php }
} ?>
<input type="text" placeholder="Anon" name="user[]">
<input type="submit" name="submit">
</form>
<?php
if(!empty($_POST['user'])){
foreach($_POST['user'] as $key => $user){
echo $user."<br />";
}
}
?>
</body>
</html>
I have started learning php recently and have confront with this error while working on localhost. I have tried all possible solutions available on the web but haven't got ridden of the problem.
I am using VS code for text editing and installed php and apache(as the webserver) on windows 10. I have trying the code to get the input and print that on the screen but this error is showing every time.
Please help me out about this
I am including the code
<!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">
<title>FORM</title>
</head>
<body>
<!--#an example showing the working of request variable-->
<form method="POST" action="<?php echo $_server['php_self'];?>">
name:- <input type="text" name="fname" id="1">
<input type="submit" value="submit">
</form>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$name = $_REQUEST['fname'];
if(empty($name))
{
echo "name is empty";
}
else
{
echo "NAME IS ";
echo $name;
}
}
?>
</body>
</html>
How can I get an HTML value to send to PHP. I would like to avoid using a form. For example I have an input:
<input name="input" id="input">Input</input>
while in PHP:
$input = $_POST['input'] --> but didn't work
or
$input = $_GET['input'] --> still didn't work
I know that I will be able to get it using form then action="another file" but I want it within a file. Please help. Thank you.
If you simply want to use js to append the input value in url variable then you can use js function as follows;
client.php
<!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>Document</title>
</head>
<body>
<input type="text" id="txt">
<a onclick="append()" id="anch" href="server.php?text">Send value</a>
</body>
</html>
<script>
function append()
{
txt=document.getElementById('txt');
anch=document.getElementById('anch');
anch.href=anch.href+"="+txt.value;
}
</script>
server.php
$variable = $_GET["input"];
echo $variable;
Output on localhost:
After clicking send value:-
Update: I just read the end of your question. If you want to show the value of input on same page/file then you can use following code;
<!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>Document</title>
</head>
<body>
<input type="text" id="txt">
<?php
if(isset($_GET['text']))
{
$text=$_GET['text'];
echo "<a onclick='append()' id='anch' href='?text=$text'>Enter Value</a>";
}
else
{
echo "<a onclick='append()' id='anch' href='?text'>Enter Value</a>";
}
?>
<br>
<?php
if(isset($_GET['text']))
echo "<div id='values'>".$_GET['text']."<div>";
?>
</body>
</html>
<script>
function append()
{
txt=document.getElementById('txt');
anch=document.getElementById('anch');
if(anch.href.match(/=/)=="=")
anch.href=anch.href+txt.value+"<br>";
else
anch.href=anch.href+"="+txt.value+"<br>";
}
</script>
Output:
Check output on phpFiddle
It seems that the way to go is to use the GET method.
You will need to access your page with the get parameters included like this:
http://localhost/index.php?input=VALUE_HERE
And in your php file:
$variable = $_GET["input"];
echo $variable;
But if you insist to use inline html elements to get data, you need to use javascript for that like this for jquery:
alert("This is the value of the input" + $("#input").val());
Don't use this
<input name="input" id="input">Input</input>
Use this
<input name="input" id="input">
I'm not that big of a genius in PHP nor in SQL but I'm getting this strange error, where I see the info that I want to send to the data base on the link and I get no errors, however my database is not getting updated.
<!DOCTYPE html>
<html lang="PT">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Alteração do produto</title>
</head>
<body>
<?php
$lig=new mysqli("localhost", "root", "", "pie");
if($lig->connect_errno != 0){
echo ("Base de dados indisponível");
}
$instrucao=$lig->prepare("UPDATE produto SET produto1 = ? , quantidade1 = ? , preco1 = ? WHERE codigo1 = ?");
$instrucao->bind_param("isid", $_GET['codigo1'], $_GET['produto1'], $_GET['quantidade1'], $_GET['preco1']);
$resultado=$instrucao->execute();
if($resultado==FALSE){
echo "<p>produto não editado</p>";
}
else {
//header( "Location: shoppinglist.php" );
}
$lig->close();
?>
<form method="get">
<label>Código: <input name="codigo1" readonly value="<?php echo $_GET['codigo1'] ?>"></label>
<label>Nome: <input name="produto1" value="<?php echo $_GET['produto1'] ?>"></label>
<label>Quantidade: <input name="quantidade1" value="<?php echo $_GET['quantidade1'] ?>"></label>
<label>Preço: <input name="preco1" value="<?php echo $_GET['preco1'] ?>"></label>
<button type="submit" value="POST">Alterar</button>
</form>
</body>
</html>
I know that there can be some syntax errors on this code, and I'm sorry if so. Thanks in advance!
try with
$instrucao->bind_param("sidi", $_GET['produto1'], $_GET['quantidade1'], $_GET['preco1'], $_GET['codigo1']);
i think you are binding the wrong params shouldn't the first one be $_GET['produto1'] (since it's the first one in the update statement..