php Number Times program - php

PHP Level = beginner
I am trying to write a simple program that displays the number-times of a particular
value when placed in the input box. I have tried to use the post method to do this but each time the program is up running and the submit button is selected, it displays the whole code of the php file 'timescalc.php'. I'll like to know what I am doing wrong, although I know that
the calculations with the if statements might be wrong.
Heres the code
<DOCTYPE html>
<html>
<head>
<title>Number Times</title>
</head>
<body>
<h1>Number Times Table Calculator</h1>
<form method="post" action="timescalc.php">
Enter Number : <input type="text" name="number"> <br>
<input type="submit" value="submit"/>
</form>
<?php
$number = $_POST['number'];
if ($number == 2, $number ++2)
{
echo $number . ;
}
else if ($number == 3, $number ++3)
{
echo $number . ;
}
else if ($number == 4, $number ++4)
{
echo $number . ;
}
else if ($number == 5, $number ++5)
{
echo $number . ;
}
else
{
echo "pick numbers from 2 to 5 only" ;
}
?>
</body>
</html>

You have numerous syntax errors in your php code but they are corrected here, you also need a webserver like WAMP SERVER to run php code. Good luck coding!
<DOCTYPE html>
<html>
<head>
<title>Number Times</title>
</head>
<body>
<h1>Number Times Table Calculator</h1>
<form method="post" action="test.php">
Enter Number : <input type="text" name="number"> <br>
<input type="submit" value="submit"/>
</form>
<?php
$number = $_POST['number'];
if ($number == 2)
{
$number = $number * 2;
echo $number ."." ;
}
else if ($number == 3)
{
$number = $number * 3;
echo $number ."." ;
}
else if ($number == 4)
{
$number = $number * 4;
echo $number ."." ;
}
else if ($number == 5)
{
$number = $number * 5
echo $number ."." ;
}
else
{
echo "pick numbers from 2 to 5 only" ;
}
?>
</body>
</html>

Related

Store post form values in hidden input array

I'm new to php and here's my code for a number guessing game. Since I don't know how to define a random number, I chose the number myself, 80. I'm trying to store all the guesses prior to the right one, and after the right guess, print them out on the screen. But I can't seem to be able to get it right since it only prints only the last guess before the right one.
Any help is appreciated!
<html>
<head>
</head>
<body>
<?php
$allguesses = array();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
foreach($_POST["tmn"] as $y){
echo $y . ',';
}
}else{
echo 'Guess lower';
}
array_push($allguesses,$t);
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
<?php
foreach($allguesses as $x){
echo "<input type ='hidden' name = 'tmn[]' value=' ".$x . " '>";
}
?>
</form>
</body>
</html>
Sessions seem the best for where you are in your learning curve.
The session allows the normal stateless http protocol to remember things between each submission of a form or forms. So we will save each guess in an array of guesses in the SESSION, which in PHP is an array as well.
<?php
session_start(); // create a session, or reconnect to an existing one
if( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["guess"]) ) {
$_SESSION['guesses'][] = $_POST["guess"]; // keep an array of guesses
// $t = $_POST["guess"]; no need for extra variables on the stack
$sayi = 80;
if($sayi > $_POST["guess"]){
echo 'Guess higher';
}elseif($sayi == $_POST["guess"]){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
foreach($_SESSION['guesses'] as $guess){
echo $guess . ',';
}
$_SESSION['guesses'] = array(); // clear the old guesses out
}else{
echo 'Guess lower';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Removed uneeded codes.
Changed method of showing previous guesses with the below code.
echo implode( ", ", $_POST["tmn"] ); // cleaner
This block handles storing previous guesses into an array that is used for displaying previous guesses.
if( isset( $_POST ) ) {
$_POST["tmn"][] = $t;
}
Fixed previous version of below block of code so that hidden <inputs> of previous guesses are outputted properly..
<?php
if( isset( $_POST["tmn"] ) ) {
foreach($_POST["tmn"] as $x){
echo "\n<input type ='hidden' name = 'tmn[]' value='$x'>";
}
}
?>
Updated Code:
<html>
<head>
</head>
<body>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
echo implode( ", ", $_POST["tmn"] );
}else{
echo 'Guess lower';
}
if( isset( $_POST ) ) {
$_POST["tmn"][] = $t;
}
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
<?php
if( isset( $_POST["tmn"] ) ) {
foreach($_POST["tmn"] as $x){
echo "\n<input type ='hidden' name = 'tmn[]' value='$x'>";
}
}
?>
</form>
</body>
</html>
For random numbers you can use rand($min, $max). to store the guesses you can use the global variable $_SESSION.
<html>
<head>
</head>
<body>
<?php
//start session (needed to use the $_SESSION variable)
start_session();
if($_SERVER["REQUEST_METHOD"] == "POST"){
//if empty -> initalize array
if (empty ($_SESSION['allguesses']){
$_SESSION['allguesses'] = array ()
}
$t = $_POST["guess"];
$sayi = 80;
if($sayi >$t){
echo 'Guess higher';
}elseif($sayi == $t){
echo "You've guessed it right!<br>";
echo 'Guessed numbers: <br>';
//echo all guesses from $_SESSION variable
foreach($_SESSION['allguesses'] as $y){
echo $y . ',';
}
}else{
echo 'Guess lower';
}
//push in $_SESSION variable
array_push($_SESSION['allguesses'],$t);
}
?>
<form method="post">
Guess the number:
<input type="number" name="guess" min ="1" max = "100"><br>
<input type="submit" name="submit">
</form>
</body>
</html>

PHP counting uppercase letters (not working)

I am new to PHP and trying to count all the uppercase letters in the text area, thought I am not able get anything when I hit the 'submit' button. Here is my code :
<!DOCTYPE html>
<html>
<body>
<?php
if(isset($_POST['submit'])) {
function caps($s) {
$u = 0;
$d = 0;
$n = strlen($s);
for ($x=0; $x<$n; $x++) {
$d = ord($s[$x]);
if ($d > 64 && $d < 91) {
$u++;
}
}
return $u;
}
$n1=$_POST['n1'];
echo 'caps: ' . caps($n1) . "\n";
}
?>
<form><textarea rows="4" cols="50" name="n1" value="<?php if(isset($_POST['n1'])){echo htmlspecialchars($_POST['n1']);}?>"></textarea>
<br><input type="submit" name="submit" value="Submit"></form>
</body>
</html>
This example will help you.
preg_match_all("/[A-Z]$/", $s, $matches);
$all_upper_cases = count($matches);
Use this function:
function count_capitals($s) {
return strlen(preg_replace('![^A-Z]+!', '', $s));
}
ex.
$n1=$_POST['n1'];
echo 'caps: ' . count_capitals($n1) . "\n";
textbox:
<textarea rows="4" cols="50" name="n1" value="<?php count_capitals($n1) ?>"></textarea>
You forgot to set the form method to post your code should be something like:
<!DOCTYPE html>
<html>
<body>
<?php
if(isset($_POST['submit'])) {
function caps($s) {
$u = 0;
$d = 0;
$n = strlen($s);
for ($x=0; $x<$n; $x++) {
$d = ord($s[$x]);
if ($d > 64 && $d < 91) {
$u++;
}
}
return $u;
}
$n1=$_POST['n1'];
echo 'caps: ' . caps($n1) . "\n";
}
?>
<form method="post"><textarea rows="4" cols="50" name="n1" value="<?php if(isset($_POST['n1'])){echo htmlspecialchars($_POST['n1']);}?>"></textarea>
<br><input type="submit" name="submit" value="Submit"></form>
</body>
</html>
Make sure you set the form method to post.
If you don't provide method the form uses get method instead of post.

Quadratic equation solver in php

I tried to make a quadratic equation solver in php:
index.html:
<html>
<body>
<form action="findx.php" method="post">
Find solution for ax^2 + bx + c<br>
a: <input type="text" name="a"><br>
b: <input type="text" name="b"><br>
c: <input type="text" name="c"><br>
<input type="submit" value="Find x!">
</form>
</body>
</html>
findx.php:
<?php
if(isset($_POST['a'])){ $a = $_POST['a']; }
if(isset($_POST['b'])){ $b = $_POST['b']; }
if(isset($_POST['c'])){ $c = $_POST['c']; }
$d = $b*$b - 4*$a*$c;
echo $d;
if($d < 0) {
echo "The equation has no real solutions!";
} elseif($d = 0) {
echo "x = ";
echo (-$b / 2*$a);
} else {
echo "x1 = ";
echo ((-$b + sqrt($d)) / (2*$a));
echo "<br>";
echo "x2 = ";
echo ((-$b - sqrt($d)) / (2*$a));
}
?>
the problem is that it's returning wrong answers (d is right,x1 and x2 are not) seems like sqrt() is returning zero or maybe something else.
There's a typo in this line:
elseif($d = 0)
which is assigning the value 0 to $d instead of comparing it. That means you are always evaluating sqrt(0), which is 0, in your else block.
It should be:
elseif($d == 0)

PHP Displaying a number of asterisks depending on the number given in the input field

What I want to accomplish is to display an asterisk or asterisks () depending on the number I input. For example if I input 2, the form will display 2 asterisks (*). In my code, I don't think string concatenation is not the right way to do it as I didn't get the result I wanted. I use a for loop. I'd appreciate if you can tell me how to code it the right way or if the for loop is wrong in this situation. Here's the code so far.
<?php
$number = $star = '';
if (isset($_POST['submit'])) {
$number = (int)$_POST['number'];
$star = '*';
for ($i = 0; $i < $number; $i++) {
$star .= $star;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Star</title>
</head>
<body>
<!--Form-->
<form id="form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<label for="number">Enter number</label>
<input id="number" type="number" name="number" size="3" maxlength="3" required>
<input type="text" readonly="readonly" value="<?php echo $star; ?>">
<input type="submit" name="submit" value="Display">
</form>
</body>
</html>
How about str_repeat()
$star = str_repeat("*", $number);
With your current code you will always get more asterixes (as mentioned in the comments by #AeJey) because you are starting with one *, you join it with itself getting **, then again join with itself getting ****...
#Unamata Sanatarai str_repeat() works nice in this situation, so use that instead.
Don't forget some error checking:
<?php
if (isset($_POST['submit'])) {
$number = (int) $_POST['number'];
if ($number > 0) {
$star = str_repeat("*", $number);
} else {
$star = "Enter number greater than zero!";
}
}
?>
Hope this helps..
`
Don't concatenate $star on $star ($star .= $star;). Choose another variable - $out .= $start and output that instead.
Or you could use the string padding function to repeat the wanted number of times.
$number = (int) $_POST["number"];
$out = str_pad("", $number, "*");
Your printed asterisks are doubleing in string length each iteration because you are concatenating the whole cached string onto itself.
Instead only add a single character to the cached string on each iteration.
Code: (Demo)
$number = 5;
$star = '*';
$stars = $star;
for ($i = 0;
$i < $number;
++$i, $stars .= $star
) {
echo "$stars\n";
}
Output:
*
**
***
****
*****

PHP rand multiple math equation generator with overall results

Basically I'm trying to display a maths equation with 2 random variables between 0,100.
I need to store 2 different variables which would be: amount of questions correct, and total questions answered.
Only by displaying one question at a time and on submit, prompting the user if they want to continue answering questions or to stop if continuing then refreshing the random values. upon stopping displaying the 3 stored variables.
in the format of " " correct and " " total questions answered.
<html>
<head>
<title></title>
<?php
function displayQuestion(){
$firstVal = rand(0,100);
$secondVal = rand(0,100);
$valTotal = $firstVal + $secondVal;
echo $firstVal . "+" . $secondVal . "=";
}
function answersCorrect(){
$answer = 0;
$firstVal = rand(0,100);
$secondVal = rand(0,100);
$valTotal = $firstVal + $secondVal;
do {$valTotal;
$answer ++;
function displayAnswer() {
if ($answer == $valTotal){
$correct ++;
$answer ++;
}
echo "<p>You got {$correct} answers correct out of {$answer}.</p>";
}
}
while ($answer == $valTotal);
$correct = 0;
}
?>
<script>
function query(){
prompt("More questions (y/n)?");
if (prompt != y || Y){
<?php
echo "answersCorrect();";
?>
} else {
function reloadPage(){
location.reload();
}
}
}
</script>
</head>
<body>
<form action="calculate_randMath.php" method="post" id="mathsForm" name="answer">
<p>Question: <?php echo displayQuestion(); ?> </p>
<p>Your answer: <input type="text" name="answer" id="$answer"/></p>
<p><input type="submit" value="answer" name="Submit" onClick="query()" /></p>
</form>
</body>
</html>

Categories