Simple POST random number issue in PHP - php

Ok I am trying to make something to ask you random multiplication questions. Now it asks the questions fine. Generates the random questions fine. But when it reloads the page the random numbers are different...
how can I fix this?
<?php
$rndnum1 = rand(1, 12);
$rndnum2 = rand(1, 12);
echo "<h3>". $rndnum1 . " x ";
echo $rndnum2 . "</h3>";
if($_SERVER["REQUEST_METHOD"] == "GET") {
$answer=0;
}
else if($_SERVER["REQUEST_METHOD"] == "POST") {
$answer=trim($_POST["answerInput"]);
$check=$rndnum1*$rndnum2;
if($answer==$check) {
echo "Correct!";
}
else {
echo "Wrong!";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="answerInput" value="<?php echo $answer; ?>" size="20"/>
</td>
<td>
<?php echo $answerError; ?>
</td>
</tr>
<tr>
<td class="signupTd" colspan="2">
<input type="submit" name="submit" value="Submit"/>
</td>
</tr>
</table>
</form>

When you reload the page, $rndnum1 and $rndnum2 are set to new random numbers via the rand() function. That's why they are not staying the same. Try passing the original random numbers along with the POST, and calculate the numbers from $_POST before checking if the answer's correct.
To do this, make sure you include the following line for both random variables in your submission form:
<input type="hidden" name="rndnum1" value="<?php echo $rndnum1 ?>" />
Then, on the next load of the page after the answer form is submitted, get the numbers with $_POST['rndnum1'], etc.

Include the generated random numbers in hidden form fields so they're submitted to the server.
For example, just inside <form>:
<input type="hidden" name="rand1" value="<?=$rndnum1?>">
<input type="hidden" name="rand2" value="<?=$rndnum2?>">
Then in PHP, when you're processing the form, use $_POST['rand1'] and $_POST['rand2'] to retreive the original numbers, multiply, then compare with the user's given answer.

add srand(0) to top of your code.
actually to you may want to use a cookie that is randomly initialised, and then pass that to srand()

Something like this should work.
<?php
#session_start();
if($_SERVER["REQUEST_METHOD"] == "GET")
{
$answer=0;
}
if (!$_POST['submit'])
{
$_SESSION['rndnum1'] = rand(1, 12);
$_SESSION['rndnum2'] = rand(1, 12);
}
else
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$answer = trim($_POST["answerInput"]);
$check = $_SESSION['rndnum1']*$_SESSION['rndnum2'];
if( $answer == $check)
{
$msg = "Correct!";
}
else
{
$msg = "Wrong!";
}
}
echo "<h3>". $_SESSION['rndnum1'] . " x " . $_SESSION['rndnum2'] . "</h3>";
if ($_POST['submit'])
{
echo $msg;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="answerInput" value="<?php echo $answer; ?>" size="20"/>
</td>
<td>
<?php echo $answerError; ?>
</td>
</tr>
<tr>
<td class="signupTd" colspan="2">
<input type="submit" name="submit" value="Submit"/>
</td>
</tr>
</table>
</form>

Related

Why do I can't get the title by using POST method?

So I am trying to get the title from the URL by using $_GET['title'] in the first PHP file, but I can't get the file on the 2nd file.
URL:
https://easy2book.000webhostapp.com/neworder.php?bookid=101&title=SENIOR%20secondary%20geography%20fieldwork%20and%20assessment%20practice%202021.%20For%20HKDSE%202021%20/%20Ip%20Kim%20Wai%20...%20[et%20al.].
1st File:
<?php
include_once 'header.php';
$id2 = mysqli_real_escape_string($conn, $_GET['bookid']);
$title2 = mysqli_real_escape_string($conn, $_GET['title']);
?>
<section class="neworder-form">
<h2>Order</h2>
<div class="neworder-form-form">
<form action="neworder.inc.php" method="post">
<table>
<tr>
<td>Book ID:</td>
<td>
<input type="text" disabled="disabled" name="bookid2" value="<?= $id2 ?>">
</td>
</tr>
<tr>
<td>Book Title: </td>
<td>
<input type="text" disabled="disabled" name="title2" value="<?= $title2 ?>">
</td>
</tr>
<tr>
<td>Username: </td>
<td>
<input type="text" name="uid2" placeholder="Username...">
</td>
</tr>
<tr>
<td>Comfirmed Book ID: </td>
<td>
<input type="text" name="id2" placeholder="Please enter the Book ID....">
</td>
</tr>
</table>
<button type="submit" name="submit2">Order</button>
</form>
</div>
<?php
// Error messages
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyinput2") {
echo "<p>Fill in all fields!</p>";
}
else if ($_GET["error"] == "usernametaken2") {
echo "<p>Username already taken!</p>";
}
}
?>
</section>
2nd File:
<?php
if (isset($_POST["submit2"])) {
// First we get the form data from the URL
$uid2 = $_POST["uid2"];
$id2 = $_POST["id2"];
$title2 = $_POST["title2"];
// Then we run a bunch of error handlers to catch any user mistakes we can (you can add more than I did)
// These functions can be found in functions.inc.php
require_once "dbh.inc.php";
require_once 'functions2.inc.php';
// Left inputs empty
// We set the functions "!== false" since "=== true" has a risk of giving us the wrong outcome
if (emptyInputOrder2($uid2,$id2) !== false) {
header("location: ../neworder.php?error=emptyinput&bookid=$id2&title=$title2");
exit();
}
// Is the username exists
if (uidExists2($conn, $uid2) !== true) {
header("location: ../neworder.php?error=undefineuser");
exit();
}
// If we get to here, it means there are no user errors
// Now we insert the user into the database
createUser($conn, $uid2, $id2);
} else {
header("location: ../neworder.php");
exit();
}
The input fields are disbled, disabled inputs are not posted.
Replace $title2 = $_POST[""]; with $title2 = $_POST["title2"];

Trouble with catching values from a multidimensional array and display it in the text field where it was originally entered when form was submitted

I need help on how to retain the entered values in the text fields where user entered the value after submit. I'm having difficulty trying to figure out how to retain the values, because when I click on the submit button, the page refreshes and then values gone, and I have to retype them again.
Below is my form:
<?php $count_name = count($x); ?>
<table>
<thead>
<tr>
<th colspan="<?php echo $count_name; ?>"><strong>MR</strong></th>
<th colspan="<?php echo $count_name; ?>"><strong>MS</strong></th>
</tr>
</thead>
<tbody>
<?php $_college = mysql_query("SELECT * FROM college");
if(mysql_num_rows($_college)) {
$i=0;
while($row_college=mysql_fetch_array($_college)) { ?>
<tr>
<?php for($j=0;$j<$count_name;$j++) { ?>
<td>
<input type="text" name="mr<?php echo $j; ?>[]" value=""/>
<td>
<?php } for($k=0;$k<$count_name;$k++) { ?>
<td>
<input type="text" name="ms<?php echo $k; ?>[]" value=""/>
<td>
<?php } ?>
</tr>
<?php } $i++;} ?>
</tbody>
<table>
<input type="hidden" value="<?php echo $count_name; ?>" name="totrows"/>
<input type="submit" value="Submit" name="submit"/>
Here's my code if button submit is click
<?php
if(isse($_POST['submit'])) {
$y = $_POST['totrows'];
$count_totcriteria = $y;
for($ab=0;$ab<$count_totcriteria;$ab++) {
$mr = 'mr_'.$ab;
$ms = 'ms_'.$ab;
$mr_score = $_POST[$mr];
$ms_score = $_POST[$mr];
foreach($mr_score as $key1 => $val1) {
if(is_numeric($val1) && !empty($val1)) {
$mr_val[] = $val1;
} else {
$msg = 'All fields are required and must be a valid score';
}
}
foreach($ms_score as $key2 => $val2) {
if(is_numeric($val2) && !empty($val2)) {
$ms_str[] = $val2;
} else {
$msg = 'All fields are required and must be a valid score';
}
}
}
}
I know I have to put some code in the 'value=""' in order to display back the entered values when form is submitted but I am not sure what code to use. Not sure how to catch each array values.
I think instead of
<input type="text" name="mr<?php echo $j; ?>[]" value=""/>
you are looking for something like this (assuming $i is your new outer loop)
<input type="text" name="mr_<?= $j ?>[<?= $i ?>]" value="<?= #$_POST['mr_'.$j][$i] ?>"/>
and the same change for the ms line.
Does that work?

Query does not work

I made this code:
Acum, bifeaza materiile pe care le studiaza clasa aleasa:<br />
<form name="servForm" action="<?php $PHP_SELF; ?>" method="post" >
<table border="0">
<?php
$a = 0;
$rezultat = "SELECT id, materie
FROM materii
ORDER BY id";
$rezultat1 = mysql_query($rezultat);
while($plm = mysql_fetch_array($rezultat1))
{
if($a++ %5 == 0) echo "<tr>";
?>
<td align="center"><input type="checkbox" name="checkbox2[]" value="<?php echo $plm['id']; ?>" /></td>
<td style="text-align:left"><?php echo $plm["materie"]; ?> </td>
<?php
if($a %5 == 0) echo "</tr>";
}
?>
</table>
</div>
<br/>
<input type="reset" value="Sterge" /> <input type="submit" value="Salveaza" name="savebtn" />
</form>
<?php
if(isset($_POST['savebtn']))
{
foreach($_POST["checkbox2"] as $loc_id)
{
$query = "INSERT INTO materii_pe_clase(id_scoala,id_clasa,id_materie) VALUES('$scoalalui','$clasalui','$loc_id')"; //aici cauta ! :))
$result5 = mysql_query($query)
or die('eroare');
}//sfarsit foreact
}//sfarsit if isset
Why does the last query not work? p.s. its a school project, so mysql is ok, no need for mysqli. p.p.s I defindet the $scoalalui and $clasalui somwhere a little up the page. but they are not the problem, i tried replacing them with values. the query simply does not work. thanks!
thank you all!
EDIT
VARDUMP for $clasalui and $scoalalui
:
string '1' (length=1)
string '1' (length=1)
Your problem here is that, you have error tool turned off, because PHP should have said, something like this.
Notice: Undefined variable $PHP_SELF"
Since you don't see it, I'd assume that, its a root of your "problem".
PHP_SELF is not a variable, that's a constant. Its not even required here, as by default PHP sends data to its target URL.
I improved readability of your code, so that should work for you now,
<?php
// You want to see all errors? Fine:
error_reporting(E_ALL);
$a = 0;
$rezultat = "SELECT id, materie FROM materii ORDER BY id";
$rezultat1 = mysql_query($rezultat);
// If the form is submitted, this will be executed
if (isset($_POST['savebtn'])) {
foreach($_POST["checkbox2"] as $loc_id) {
$query = "INSERT INTO `materii_pe_clase` (`id_scoala`, `id_clasa`, `id_materie`) VALUES('$scoalalui', '$clasalui', '$loc_id')";
$result = mysql_unbuffered_query($query);
if (!$result){
die(mysql_error());
}
}
// And finally
die('Saved. Thanks');
}
?>
Acum, bifeaza materiile pe care le studiaza clasa aleasa: <br />
<form name="servForm" method="POST">
<table border="0">
<?php while($plm = mysql_fetch_array($rezultat1)) : ?>
<?php if ($a++ %5 == 0) :?>
<tr>
<?php endif; ?>
<td align="center">
<input type="checkbox" name="checkbox2[]" value="<?php echo $plm['id']; ?>" />
</td>
<td style="text-align:left"><?php echo $plm["materie"]; ?> </td>
<?php if($a %5 == 0) : ?>
</tr>
<?php endif; ?>
<?php endwhile; ?>
</table>
<br/>
<input type="reset" value="Sterge" />
<input type="submit" value="Salveaza" name="savebtn" />
</form>

Html multiple select field issue with php

I've a html form with multiple select field. I'm trying to validate it with php. but i can't validate this multiple select field with php. It's show me success message without any validation.
Please kindly tell me what's the problem in my code. Thank you.
Php Code:
<?php
if(isset($_POST['Submit']) && $_POST['Submit'] == "Send SMS")
{
if(isset($_POST['number']))
$number = $_POST['number'];
$msg = inputvalid($_POST['txt']);
$err = array();
if(isset($msg) && isset($number))
{
if(empty($msg) && empty($number))
$err[] = "All field require";
else
{
if(empty($msg))
$err[] = "Your message require";
if(empty($number))
$err[] = "Select your mobile number";
}
}
if(!empty($err))
{
echo "<div class='error'>";
foreach($err as $er)
{
echo "<font color=red>$er.</font><br/>";
}
echo "</div>";
echo "<br/>";
}
else
{
echo "good";
}
}
?>
Html Code:
<form name="frm" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<table width="800" border="0" cellspacing="10" cellpadding="0">
<tr>
<td valign="top">Number</td>
<td>
<select multiple="multiple" size="10" name="number[]">
<option value="">--Select Member--</option>
<?php
$class = mysql_query("SELECT * FROM e_members");
while($res = mysql_fetch_array($class))
{
$phone = $res['phone'];
?>
<option value="<?php echo $phone; ?>"> <?php echo $phone; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td valign="top">Write message</td>
<td>
<textarea class="textarea" placeholder="Your message" name="txt" onkeyup="counter(this);">
<?php if(isset($_POST['txt'])) echo $_POST['txt']; ?>
</textarea>
<br/>
<input type="" name="lbl" style="border:none;">
<br/>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="Submit2" value="Save SMS" class="view"/>
<input type="submit" name="Submit" value="Send SMS" class="submit"/>
</td>
</tr>
</table>
</form>
Update:
After select multiple/single value var_dump showing:
array(1) { [0]=> string(13) "8801814758545" }
Without select it's showing:
NULL
You are trying to validate array $number using empty($number). It won't work as you expected
You can validate this as if (is_array($number) && count($number) > 0)
The problem is that your check for empty values is inside for check for if(isset($msg) && isset($number)) and as soon as you post the form these variables are set. As you are already check that the post is set then remove this outer if statement and just check for empty values and it should work.

unable to get the value of the text field with the help of respective checkboxes. please help

I've a doubt. I've 3 textboxes and each is having checkboxes next to it. I want to display
the values of only those textboxes whose respective checkboxes are clicked. Following is the attached HTML and PHP codes:
<html>
<head>
</head>
<body>
<form name="f" method="post" action="4.php">
<table>
<tr>
<th> Facility </th>
</tr>
<tr>
<td><input type="text" name="a1" value="a"></td><td><input type="checkbox" id="facility[]" name="facility[]" value="Hostel"></td>
</tr>
<tr>
<td><input type="text" name="b1" value="b"></td><td><input type="checkbox" id="facility[]" name="facility[]" value="Transport"></td>
</tr>
<tr>
<td><input type="text" name="c1" value="c"></td><td><input type="checkbox" id="facility[]" name="facility[]" value="Food"></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
and below is the PHP part.
<?php
$a=$_POST['a1'];
$b=$_POST['b1'];
$c=$_POST['c1'];
$facilityArray = $_POST['facility'];
$facility = "";
if(count($facilityArray) > 0)
{
foreach($facilityArray as $fac)
{
$facility .= " " . $fac;
}
}
echo $facility; echo "<br>";
echo $a; echo "<br>";
echo $b; echo "<br>";
echo $c;
?>
With the help of following codes I am able to display all the values of checked checkboxes. I am also able to display the values of all the textboxes. But I actually want to display the values of only those textboxes whose respective checkboxes are clicked. I know it may be a very basic question but please help me grow in PHP. Thanks in advance... :(
Your textboxes should also be in an array post to achieve this.
To achieve this change the input lines as:
<td><input type="text" name="textboxes[]" value="a"></td><td><input type="checkbox" id="facility[]" name="facility[]"></td>
From php you'll be getting the posted textboxes in an array as:
$textbox=$_POST['textboxes'];
You should then loop through the checkboxes array and if the corresponding checkbox is "on" (clicked), then display the textboxes value. To do this you would also need a counter to make sure you are on the same array index for both checkboxes and textboxes:
if(count($facilityArray) > 0)
{
$i = 0;
foreach($facilityArray as $fac)
{
if($fac == "on")
{
echo $textbox[$i] . "</br>";
}
$i ++;
}
}
I've also added a name to your submit button so you only check the form when it is submitted.
Your page should now look something like this:
<?php
if(isset($_POST['submit']))
{
$textbox=$_POST['textboxes'];
$facilityArray = $_POST['facility'];
if(count($facilityArray) > 0)
{
$i = 0;
foreach($facilityArray as $fac)
{
if($fac == "on")
{
echo $textbox[$i] . "</br>";
}
$i ++;
}
}
}
?>
<form name="f" method="post" action="4.php">
<table>
<tr>
<th> Facility </th>
</tr>
<tr>
<td><input type="text" name="textboxes[]" value="a"></td><td><input type="checkbox" id="facility[]" name="facility[]"></td>
</tr>
<tr>
<td><input type="text" name="textboxes[]" value="b"></td><td><input type="checkbox" id="facility[]" name="facility[]"></td>
</tr>
<tr>
<td><input type="text" name="textboxes[]" value="c"></td><td><input type="checkbox" id="facility[]" name="facility[]"></td>
</tr>
<tr>
<td colspan="3"><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
UPDATE:
To make sure that the $_POST variable exists before assigning it to a variable we use the isset(). In your case just update the php segment as:
<?php
if(isset($_POST['submit']))
{
if(isset($_POST['textboxes']))
{
$textbox=$_POST['textboxes'];
if(isset($_POST['facility']))
{
$facilityArray = $_POST['facility'];
if(count($facilityArray) > 0)
{
$i = 0;
foreach($facilityArray as $fac)
{
if($fac == "on")
{
echo $textbox[$i] . "</br>";
}
$i ++;
}
}
}
}
}
?>
Where the only changes are the addition of another two if statements that take a boolean flag from the isset() function according to whether the $_POST variable has been posted successfully
if(isset($_POST['textboxes']))
AND
if(isset($_POST['facility']))

Categories