I just started my module on php for school, having completed Javascript two months ago I am familiar with a lot of the elements but a bit rusty. Basically I setup a form with html and added a bit of css to make it pretty. The school is making us do some generic exercices. I now how to grab values etc using this with Javascript
document.getElementById("textBox").value;
and to return the output through my div I created with
document.getElementById("return").innerHTML = ... ;
I honestly can't figure out how to do this with php and I am sure it's real easy but can't for the life of me find a solution online and the schools videos are very vague.
The exerciser is "Create an application that ask the user for number (1-7) and return the day of the week associate with the number entered. You must validate the number"
This is the code I have so far....
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>PHP exercise 1</title>
<link rel="stylesheet" type="text/css" href="./styling1.css"/>
</head>
<body>
<!--E X C E R S I S E 3 !-->
<section id="allContent">
<section>
<button class="hide" id="clic"> <h4> E X E R C I C E 1 </h4></button>
</section>
<div id="container" class="hidden">
<div id="Barbox"><p class="pClass"> Create an application that ask the user for number (1-7) and return the day of the week associate with the number entered. You must validate the number</p>
</div>
<div id="background"></div>
<div class="ball"></div><div id="ball2"></div>
<div id="titleBox">
<p id="titlePRG">Enter a number!</p>
</div>
<form>
<input type="text" value="<?php echo $number = 1 ; ?>" id="textField">
<input type="button" value="Enter" class="button" onclick="return_day()">
</form>
<div id="valueReturned">
<p id="returnText"><p>
</div>
<h3> Next Exercise </h3>
</div>
</section>
<?php
function return_day(){
$number = 1 ;
if ($number == 1){
echo "The day of the week is Monday";
}
else if ($number == 2){
echo "The day of the week is Tuesday";
}
else if ($number == 3){
echo "The day of the week is Wednesday";
}
else if ($number == 4){
echo "The day of the week is Thursday";
}
else if ($number == 5){
echo "The day of the week is Friday";
}
else if ($number == 6){
echo "The day of the week is Saturday";
}
else if ($number == 7){
echo "The day of the week is Sunday";
}
else{
echo ("Wrong input, try again!");
}
}//end of function
?>
This is what the browser looks like if it makes any difference so you understand my question
The answer is supposed to display in the white box at the bottom which is
Unlike Javascript, php is totally different! Javascript's functions can be accessed in HTML by using onclick, onload, etc. attributes, but php's functions are quite different and can only be accessed through php codes. First you need to create a prom with a method and then send to the same page(in your case) and then run the conditions that you have applied and at last echo the result as i have done in it.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<title>PHP exercise 1</title>
<link rel="stylesheet" type="text/css" href="./styling1.css" />
</head>
<body>
<!--E X C E R S I S E 3 !-->
<section id="allContent">
<section>
<button class="hide" id="clic">
<h4> E X E R C I C E 1 </h4>
</button>
</section>
<div id="container" class="hidden">
<div id="Barbox">
<p class="pClass"> Create an application that ask the user for number (1-7) and return the day of the week associate with the number entered. You must validate the number</p>
</div>
<div id="background"></div>
<div class="ball"></div>
<div id="ball2"></div>
<div id="titleBox">
<p id="titlePRG">Enter a number!</p>
</div>
<form method="get" action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="text" value="" id="textField" name="number">
<input type="submit" value="Enter" class="button" name="submit">
</form>
<?php
if (isset($_GET['submit']))
$number = isset($_GET['number']) ? $_GET['number'] : '';
if ($number == 1) {
$returntext = "The day of the week is Monday";
} else if ($number == 2) {
$returntext = "The day of the week is Tuesday";
} else if ($number == 3) {
$returntext = "The day of the week is Wednesday";
} else if ($number == 4) {
$returntext = "The day of the week is Thursday";
} else if ($number == 5) {
$returntext = "The day of the week is Friday";
} else if ($number == 6) {
$returntext = "The day of the week is Saturday";
} else if ($number == 7) {
$returntext = "The day of the week is Sunday";
} else {
$returntext = ("Wrong input, try again!");
}
?>
<div id="valueReturned">
<p id="returnText"><?php echo $returntext; ?><p>
</div>
<a href="index4.html" id="jButton">
<h3> Next Exercise </h3>
</a>
</div></section>
Hope that, you must be running these php codes in a suitable server! Good go!
Below code should help you understand.
<?php
$response = "";
if(isset($_POST) && isset($_POST["mytext"])): /// check if user submitted form
$num = $_POST["mytext"]; //put form mytext variable.. retrieved from html <input name="mytext"....
if(is_numeric($num)):
switch($num):
case "1":
$response = "Monday";
break;
case "2":
$response = "Tuesday";
break;
case "3":
$response = "Wednesday";
break;
case "4":
$response = "Thursday";
break;
case "5":
$response = "Friday";
break;
case "6":
$response = "Saturday";
break;
case "7":
$response = "Sunday";
break;
default:
$response = "Invalid number";
endswitch;
else:
$response = "Invalid number";
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PhpFiddle Initial Code</title>
<!--
http://phpfiddle.org
-->
<script type="text/javascript">
</script>
<style type="text/css">
</style>
</head>
<body>
<div style="margin: 30px 10%;">
<h3>My form</h3>
<form id="myform" name="myform" action="" method="post">
<label>Text</label> <input type="text" value="" size="30" maxlength="100" name="mytext" id="" /><br /><br />
<br />
<button id="mysubmit" type="submit">Submit</button><br /><br />
<?php if (isset($_POST)): ?>
<div style="background-color:red;color:white;"><?php echo $response; ?></div>
<?php endif; ?>
</div>
</form>
</div>
<?php
?>
</body>
</html>
Related
I have mainly two question first describe what I going to do. I've created some animal in the code by saying that octopus will have 8 leggs,9 brain,1 stomach,3 heart similarly for other property.And by a html form using post method I'm taking input from user as showing the animals image if the description matches.
I've also declared the corresponding animals name.I want to also show the name of the animal after matching(by printing $name).
2)Here I'm matching user input for each animal(by using if,elseif elseif) but how can I optimize so that if there is more than 100 animal I don't have to do 100 else if.
Here is my code.
<?php
class animal{
var $name;
var $brain;
var $stomach;
public $heart;
public $leg;
function __construct($aBrain, $aStomach, $aHeart, $aLeg)
{
$this->brain = $aBrain;
$this->stomach = $aStomach;
$this->heart = $aHeart;
$this->setLeg($aLeg);
}
function isBipedal(){
if ($this->leg == 2) {
return "it is a bipedal animal";
}else {
return "it is not a bipedal animal";
}
}
function getLeg(){
return $this->leg;
}
function setLeg($leg){
if ($leg == 8 ||$leg == 4 ||$leg == 2) {
$this->leg= $leg;
}else {
$this->leg= "non-pedal";
}
}
}
$octopus = new animal(9,1,3,8);
$cow = new animal(1,4,1,4);
$human = new animal(1,1,1,2);
$octopus->setLeg(8);
//echo "new leg ".$octopus->leg = 0;
echo "<br>".$octopus->getleg();
echo "<br>".$human->isBipedal(). "<br>";
if(isset($_POST['submit'])) {
if(isset($_POST['brain'])
&& isset($_POST['stomach'])
&& isset($_POST['heart'])
&& isset($_POST['leg']) ){
$myBrain = $_POST['brain'];
$myStomach = $_POST['stomach'];
$myHeart = $_POST['heart'];
$myLeg = $_POST['leg'];
// echo "brain = ". $myBrain. "<br>";
// echo "stomach = ". $myStomach. "<br>";
// echo "heart = ". $myHeart. "<br>";
// echo "leg = ". $myLeg. "<br>";
if($myBrain==$octopus->brain
&& $myStomach==$octopus->stomach
&& $myHeart==$octopus->heart
&& $myLeg==$octopus->leg
){
?>
<div class="animal-info">
<div><p class="blinking">You are Octopus</p></div>
<img src="media/octopus.jpg" alt="" class="animal-img">
<img src="media/octopus.gif" alt="" class="animal-img">
</div>
<?php
}
elseif($myBrain==$cow->brain
&& $myStomach==$cow->stomach
&& $myHeart==$cow->heart
&& $myLeg==$cow->leg
){
?>
<div class="animal-info">
<div>
<span class="blinking">You are Cow</span>
</div>
<img src="media/cow.jpg" alt="" class="animal-img">
<img src="media/cow.gif" alt="" class="animal-img">
</div>
<?php
}
elseif($myBrain==$human->brain
&& $myStomach==$human->stomach
&& $myHeart==$human->heart
&& $myLeg==$human->leg
){
?>
<div class="animal-info">
<div>
<span class="blinking">You are Human</span>
</div>
<img src="media/human.jpg" alt="" class="animal-img">
<img src="media/human.gif" alt="" class="animal-img">
</div>
<?php
}else{
echo "you don't match with anything at all";
}
}
}
?>
<!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>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="post">
<span>How many brain you have?</span>
<input type="text" name="brain" id="brain">
<br>
<span>How many stomach you have?</span>
<input type="text" name="stomach" id="stomach">
<br>
<span>How many heart you have?</span>
<input type="text" name="heart" id="heart">
<br>
<span>How many leg you have?</span>
<input type="text" name="leg" id="leg">
<br>
<input type="submit" name="submit" value="Let me see">
</form>
</body>
</html>
u should either store them in a DB and make a query, or store them in array and search by some linq equivalent in php
Could You try with a Switch case?
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Welcome to my guessing game</h1>
<form action="" method="GET">
<label for="numinput">Enter your number</label>
<input type="text" name="numinput">
<input type="submit" name="submit">
</form>
<?php
$num = $_GET['numinput'];
if (!isset($_GET['num'])) {
echo("Missing Guess Parameter");
} elseif ( strlen($_GET['num']) <60){
echo ("Your guess is too short");
} elseif ( !is_numeric($_GET['num'])){
echo("Your guess is not a number");
} elseif ($_GET['num'] > 60){
echo ("Your guess is too high");
} else {
echo ("Congratulations - You are right");
}
?>
</html>
My goal is to create a simple number guessing game using $_GET in php
Output: "Missing Guess Parameter" despite i provide any number in the input. Also, I couldn't understand whether to get the user provided data from submit of the textbox.
You need to put $num instead of $_GET['num'] after the variable $num is set
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Welcome to my guessing game</h1>
<form action="" method="GET">
<label for="numinput">Enter your number</label>
<input type="text" name="numinput">
<input type="submit" name="submit">
</form>
<?php
$num = $_GET['numinput'];
if (!isset($num)) {
echo("Missing Guess Parameter");}
elseif ( strlen($num) <60){
echo ("Your guess is too short");}
elseif( !is_numeric($num)){
echo("Your guess is not a number");}
elseif ($num > 60){
echo ("Your guess is too high");}
else{
echo ("Congratulations - You are right");}
?>
</html>
Name of the html input and the key of $_GET must be identical, so change name="numinput" to name="num" will be a solution to fixed the problem.
NB: $num = $_GET['num']; may accure UNDEFINED INDEX if you use it outside the if condition when isset($_GET['num']) equal to true
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Welcome to my guessing game</h1>
<form action="" method="GET">
<label for="numinput">Enter your number</label>
<input type="text" name="num">
<input type="submit" name="submit">
</form>
<?php
//$num = $_GET['num']; this should be after isset($_GET['num']) == true
if (!isset($_GET['num'])) {
echo("Missing Guess Parameter");
} elseif ( strlen($_GET['num']) <60){
echo ("Your guess is too short");
} elseif ( !is_numeric($_GET['num'])){
echo("Your guess is not a number");
} elseif ($_GET['num'] > 60){
echo ("Your guess is too high");
} else {
echo ("Congratulations - You are right");
}
?>
</body>
</html>
I wanted to make specific letter counter, but my counter is not increasing more that once. Can some one explain what i'm doing wrong?
Here is my code:
PHP:
<?php
$count_s = 0;
$count_v = 0;
$input = '';
if(filter_has_var(INPUT_POST, 'submit')) {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['inp'];
switch($input) {
case 'v':
$count_v++;
case 's':
$count_s++;
}
}
}
?>
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Enter Symbol: </h3>
<form action="index.php" method="POST">
<input type="text" class="input" name='inp' maxlength="1" >
<button class="btn" type="submit" name="submit">Submit</button>
</form>
<div class="output">
<?php
echo "Count of letter 'V': ".$count_v."<br/>";
echo "Count of letter 'S': ".$count_s."<br/>";
?>
</div>
</body>
</html>
Try this it will be work perfectly. paste it in any test file. This will retain no of times you input v and no of times you input s, value of s and v will remain same of input some other value.
<?php
$input = '';
if(!isset($count_v))
{
$count_v=0;
}
if(!isset($count_s))
{
$count_s=0;
}
if (filter_has_var(INPUT_POST, 'submit'))
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$input = $_POST['inp'];
switch ($input)
{
case 'v':
$_POST['count_v']++;
$count_v=$_POST['count_v'];
$count_s=$_POST['count_s'];
break;
case 's':
$count_v=$_POST['count_v'];
$_POST['count_s']++;
$count_s=$_POST['count_s'];
break;
default:
$count_v=$_POST['count_v'];
$count_s=$_POST['count_s'];
break;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Enter Symbol: </h3>
<form method="POST">
<input type="hidden" name='count_v' value="<?php echo $count_v?>">
<input type="hidden" name='count_s' value="<?php echo $count_s?>">
<input type="text" class="input" name='inp' maxlength="1" >
<button class="btn" type="submit" name="submit">Submit</button>
</form>
<div class="output">
<?php
echo "Count of letter 'V': " . $count_v . "<br/>";
echo "Count of letter 'S': " . $count_s . "<br/>";
?>
</div>
</body>
</html>
you need to store counters in each request, because the variables lifetime is short (request life time), then they will be re-init from 0
to do this you can store the counters in file, database, or session
it depends on the time you want them to persist.
below is a sample for using session
** note the new line session_start(); you need to add it.
<?php
session_start();
$count_s = 0;
$count_v = 0;
$input = '';
if(filter_has_var(INPUT_POST, 'submit')) {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['inp'];
switch($input) {
case 'v':
if(!isset($_SESSION["count_v"])){
$_SESSION["count_v"] = 0;
}
$tmp = $_SESSION["count_v"];
$tmp++;
$_SESSION["count_v"] = $tmp;
break;
case 's':
if(!isset($_SESSION["count_s"])){
$_SESSION["count_s"] = 0;
}
$tmp = $_SESSION["count_s"];
$tmp++;
$_SESSION["count_s"] = $tmp;
break;
}
}
}
?>
and to read the values (in html page) use this:
<?php
echo "Count of letter 'V': ".$_SESSION["count_v"]."<br/>";
echo "Count of letter 'S': ".$_SESSION["count_s"]."<br/>";
?>
if you are going to store more than the 2 letters (s and v) then you can make the session key "count_v" generated dynamically using input itself. this will be a much less code, you will not need a switch/case
Edit: as i saw in your comment above, yes you can maintain counter values using hidden fields in HTML page, and use them to initialize the $count_s and $count_v instead of zero. you need to take care of first request when hidden values might be unset, or they could be zero
I need to modify a block of code and add a counter regarding how many times it took the user to guess the right number.
I was wondering how it would be properly implemented into my code.
This is what I have so far.
<?php
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$count++; //Declare the variable $count to increment by 1.
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
You have to use PHP Sessions to keep track of the count.
All you have to do is initialize counter to 0 and have it increment when the user guesses a number
<?php
session_start();
if (!isset($_POST["guess"])) {
$_SESSION["count"] = 0; //Initialize count
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
echo $_POST["numtobeguessed"];
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else { // must be equivalent
$_SESSION["count"]++;
$message = "Well done! You guessed the right number in ".$_SESSION["count"]." attempt(s)!";
unset($_SESSION["count"]);
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
This should work for you.
$count = isset($_POST['count']) ? $_POST['count'] : 0; //Use post value if defined. If not set to 1.
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
$count++;
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<input type="hidden" name="count"
value="<?php echo $count; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
on 22.6.2021 i wrote a Guess Number in Range [0 .. aMaxIntValue] sample Web Application using PHP. i think the following code may help you. the code is kept in a Single PHP file. it generates #4 HTML pages ...
the 1st initial page is used to collect application parameters (e.g. the Max Int Number to Guess)
the 2nd page is the Main Play Game Page where the user is asked to Guess the Secret Number or to Reset Game. this page shows the previous user guesses and some tips for the user about the guess
the 3rd page is used to notify the user looses game (that is he has no more tries left)
the 4th page is used to notify the user wins the game (that is the Guess was OK)
the Number of Tries left to the User is computed using the values range [0 .. max]
the Secret Number to Guess is a random generated integer number
this is the PHP + HTML code ...
<?php
session_start();
error_reporting (E_PARSE | E_COMPILE_ERROR);
function ResetGame()
{
unset ( $_SESSION['theMaxNumber'] );
}
function InitGame()
{
$_SESSION['theNumberToGuess'] = mt_rand (0, $_SESSION['theMaxNumber']);
$_SESSION['theMaxNumberOfTries'] = floor ( log ($_SESSION['theMaxNumber'], 2) ) + 1;
$_SESSION['theUserTriesCount'] = 0;
$_SESSION['thePrevGuessesString'] = '';
$_SESSION['theUserGuess'] = 0;
}
function ComputeNumberOfTriesLeft()
{
return $_SESSION['theMaxNumberOfTries'] - $_SESSION['theUserTriesCount'];
}
function IsNoMoreTriesLeft()
{
return ComputeNumberOfTriesLeft() <= 0;
}
$aCanPlayGame = false;
$aUserSubmittedGuess = false;
$aIsNoMoreTriesLeft = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( isset ($_REQUEST['playgame']) ) {
$_SESSION['theMaxNumber'] = intval($_REQUEST['theMaxNumber']);
// init game ...
InitGame();
$aCanPlayGame = true;
}
elseif ( isset ($_REQUEST['submituserguess']) ) {
$aCanPlayGame = true;
$aUserSubmittedGuess = true;
$_SESSION['theUserGuess'] = intval($_REQUEST['theUserGuess']);
}
elseif ( isset ($_REQUEST['resetgame']) ) {
ResetGame();
}
else {
ResetGame();
}
}
else {
ResetGame();
}
// check a play
$aUserShouldTryLower = false;
$aUserShouldTryHigher = false;
$aUserWins = false;
$aUserLooses = false;
if ($aCanPlayGame) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ( ! $aIsNoMoreTriesLeft ) {
// user have tries left
if ($aUserSubmittedGuess) {
// check user guess ...
$aUserGuess = intval($_SESSION['theUserGuess']);
if ( $aUserGuess > $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryLower = true;
}
elseif ( $aUserGuess < $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryHigher = true;
}
else {
$aUserWins = true;
// also reset game
ResetGame();
}
// add the current guess to the prev guesses string
$_SESSION['thePrevGuessesString'] .= $_SESSION['theUserGuess'] . ' ';
// increase the user tries count
++ $_SESSION['theUserTriesCount'];
// check tries count
if ( ! $aUserWins ) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ($aIsNoMoreTriesLeft) {
// this was the last try
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
}
}
else {
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
?>
<?php if ($aUserLooses): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Sorry, you loose the game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aUserWins): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Congrats, you Win the Game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aCanPlayGame): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>the Max Number is <?php echo $_SESSION['theMaxNumber']; ?></p>
<p>Guess a Number in the Range [ 0 .. <?php echo ($_SESSION['theMaxNumber']); ?> ]</p>
<p>[DEBUG] the secret number to guess is <?php echo $_SESSION['theNumberToGuess']; ?></p>
<p>you have <?php echo ComputeNumberOfTriesLeft(); ?> tries left</p>
<form method="post">
<label for="theUserGuess">Enter your Guess: </label>
<input type="text" id="theUserGuess" name="theUserGuess">
<input type="submit" name="submituserguess" value="Guess">
<input type="submit" name="resetgame" value="reset game">
</form>
<p>Prev Guesses: <?php echo $_SESSION['thePrevGuessesString']; ?> </p>
<p>
<?php
if ($aUserShouldTryLower) {
echo 'you should try a lower < guess';
}
elseif ($aUserShouldTryHigher) {
echo 'you should try a higher > guess';
}
else {
echo 'no guess';
}
?>
</p>
</body>
</html>
<?php else: ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Guess a Number from (0) to ... </p>
<form method="post">
<input id="theMaxNumber" name="theMaxNumber">
<input type="submit" name="playgame" value="play game">
</form>
</body>
</html>
<?php endif; ?>
that's all folks ...
So i have a form here, and I want on the to do some php so that if the field is empty, it will say once you submit the form after it loads to the post page, that sorry you entered no date. I also want to add strip tags, however I am unsure how, if they go on the posting_wall or if they go in the form.php? I want to use strip all tags.
I believe the empty validation was if(!empty(($date)) { echo "sorry you did not enter a date"; } but i could not get it to work.
Thank you in advance if you can help me with this. I will post the form.php and the posting wall below.
Form.php
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/index.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<link type="text/css" rel="stylesheet" href="../css/header.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
$('form').submit(function (e) {
var value;
// "message" pattern : from 3 to 150 alphanumerical chars
value = $('[name="message"]').val();
if (!/^[-\.a-zA-Z\s0-9]{3,150}$/.test(value)) {
alert('Sorry, only alphanumerical characters are allowed and 3-150 character limit".');
e.preventDefault();
return;
}
// "name" pattern : at least 1 digit
value = $('[name="name"]').val();
if (!/\d+/.test(value)) {
alert('Wrong value for "name".');
e.preventDefault();
return;
}
});
});
</script>
</head>
<body>
<?php include 'header.php' ?>
<form action="index.php" method="get">
<div id="container">
Username:*<input type="text" name="name" pattern="{3,15}" title="Letters and numbers only, length 3 to 15" required autofocus><br>
E-mail:* <input type="email" name="email" maxlength="20" required><br>
Post:*<br>
<textarea rows="15" cols="50" name='message'></textarea>
</div>
Date this event took place: <input type="text" name='date' id="datepicker" > <br>
Your favorite website is: <input type="text" name="website">
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br>
<input type="reset" value="Reset">
<input type="submit">
</form>
<p> Fields with * next to them are required </p>
<p>Posting Wall</p>
<div id="time">
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'The time at which you are posting is:'. date('h:i Y-m-d') ."\n";
?>
</div>
<?php include 'footer.php' ?>
</body>
</html>
Posting wall
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/post.css" />
<link type="text/css" rel="stylesheet" href="../css/heaader.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
</head>
<body>
<h1>Daily Dorm News </h1>
<h2> You're best place for the latest dorm news from campus </h2>
<div id="container"> <?php if ( isset($_GET['name']) and preg_match("/^[A-Za-z0-9]+$/", $_GET['name']) ) {
echo $_GET['name'];
} else {
echo "You entered an invalid name!\n";
}
?><br>
Your email address is: <?php if ( isset($_GET['email']) and preg_match("/.+#.+\..+/i", $_GET['email']) ) {
echo $_GET['email'];
} else {
echo "You didn't enter a proper email address!\n";
}
?><br>
You Posted : <?php if ( isset($_GET['message']) and preg_match("/^[-\.a-zA-Z\s0-9]+$/", $_GET['message']) ) {
echo $_GET['message'];
} else {
echo "The message is not valid! The message box was blank or you entered invalid symbols!\n";
}
?>
This event happened :<?php echo $_GET["date"]; ?><br>
Your gender is:<?php echo $_GET["gender"]; ?><br>
Your favorite website is: <?php echo $_GET["website"]; ?><br>
</div>
<?php
/* [INFO/CS 1300 Project 3] index.php
* Main page for our app.
* Shows all previous posts and highlights the current user's post, if any.
* Includes a link to form.php if user wishes to create and submit a post.
*/
require('wall_database.php');
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$gender = strip_tags($_REQUEST['gender']);
$website = strip_tags($_REQUEST['website']);
$is_valid_post = true;
// Checking if a form was submitted
if (isset($_REQUEST['name'])){
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$gender = strip_tags($_REQUEST['gender']);
$website = strip_tags($_REQUEST['website']);
// Saving the current post, if a form was submitted
$post_fields = array();
$post_fields['name'] = $name;
$post_fields['email'] = $email;
$post_fields['message'] = $message;
$post_fields['date'] = $date;
$post_fields['gender'] = $gender;
$post_fields['website'] = $website;
$success_flag = saveCurrentPost($post_fields);
}
//Fetching all posts from the database
$posts_array = getAllPosts();
?>
<?php
if(isset($name)) {
echo "<h3>Thanks ".$name." for submitting your post.</h3>";
}
?>
<div id="logo"> Don't forget to tell all you're friends about Daily Dorm News! <br> The only dorm news website on campus!</div>
<p id="received">Here are all the posts we have received.</p>
<ul id="posts_list">
<?php
// Looping through all the posts in posts_array
$counter = 1;
foreach(array_reverse($posts_array) as $post){
$alreadyPosted = false;
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
$date = $post['date'];
$gender = $post['gender'];
$website = $post['website'];
if ($counter % 2==1)
$li_class = "float-left";
else
$li_class = "float-right";
if ($name == $_GET['name']) {
$alreadyPosted = true;
}
echo '<div class=post';
if ($alreadyPosted) {
echo ' id="highlight"';
}
echo '>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' email is: '.$email.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' wrote '.$message.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>This event occured on '.$date.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>Your a '.$gender.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>You said your favorite website is '.$website.'</span></h3></li>';
echo '</div>';
}
?>
</ul>
</div>
<p id="submit">Would you like to submit another post?</p>
<?php require 'footer.php' ?>
</body>
</html>
You can check through jquery in the submit function
var datepicker=$("#datepicker").val();
if(datepicker=='') { alert('Please enter date'); return false; }
It should be
if(empty(($date)) {
echo "sorry you did not enter a date";
}
NOT
if(!empty(($date)) {
echo "sorry you did not enter a date";
}
The first expression will print "sorry you did not enter a date" if the date field is empty. The second expression will print that message if the date field is not empty.
You can try the code below. It will print 'This is an empty string'
<?php
$date = '';
if (empty($date)) {
echo 'This is an empty string';
}
if (!empty($date)) {
echo 'The date is ' . $date;
}