I'm very new to PHP. For a class assignment, we need to make a Tic Tac Toe game. So far, this is my code:
<html>
<body>
<h1>Tic Tac Toe</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="input">
<input type="submit" name="submit">
</form>
<?php
//Display Determinations
//Top Left
if (!ISSET($_POST['submit'])) {
$GLOBALS['ul_truefalse'] = true;
$GLOBALS['turn'] = 1;
$this_happened = "!isset";
}
if (ISSET($_POST['submit'])) {
$GLOBALS['turn'] = $GLOBALS['turn'] + 1;
if ($GLOBALS['turn'] == 3) {
$GLOBALS['turn'] = 1;
}
}
if ($GLOBALS['ul_truefalse'] == true) {
$GLOBALS['ul_display'] = "UL";
if (ISSET($_POST['input']) and $_POST['input'] == "ul" and $GLOBALS['turn'] == 1) {
$GLOBALS['ul_display'] = "X";
$GLOBALS['ul_truefalse'] = false;
$this_happened = "p1 ul";
}
if (ISSET($_POST['input']) and $_POST['input'] == "ul" and $GLOBALS['turn'] == 2) {
$GLOBALS['ul_display'] = "O";
$GLOBALS['ul_truefalse'] = false;
}
}
echo "Player " . $GLOBALS['turn'] . ", it's your turn!";
echo $this_happened;
?>
<table border="1" width="40%">
<tr>
<td><?php echo $GLOBALS['ul_display'] ?></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
Here is the output (left side is when the page is loaded, right side is when player 1 enters "ul"): http://i.imgur.com/G0JaXYY.png
The problem is when if (!ISSET($_POST['submit'])) { becomes false, the strings defined in that if statement lose their values, causing the undefined variable errors. I tried storing them in a hidden form box, but it didn't fix the issue. I sent my code to a person from a forum, and he said it worked. Why is this happening? How do I fix this?
Try this:
<html>
<body>
<h1>Tic Tac Toe</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="input">
<input type="submit" name="submit">
</form>
<?php
if(!session_id())
session_start();
//Display Determinations
//Top Left
if (!ISSET($_POST['submit'])) {
$_SESSION['ul_truefalse'] = true;
$_SESSION['turn'] = 1;
$this_happened = "!isset";
}
if (ISSET($_POST['submit'])) {
$_SESSION['turn'] = $_SESSION['turn'] + 1;
if ($_SESSION['turn'] == 3) {
$_SESSION['turn'] = 1;
}
}
if ($_SESSION['ul_truefalse'] == true) {
$_SESSION['ul_display'] = "UL";
if (ISSET($_POST['input']) and $_POST['input'] == "ul" and $_SESSION['turn'] == 1) {
$_SESSION['ul_display'] = "X";
$_SESSION['ul_truefalse'] = false;
$this_happened = "p1 ul";
}
if (ISSET($_POST['input']) and $_POST['input'] == "ul" and $_SESSION['turn'] == 2) {
$_SESSION['ul_display'] = "O";
$_SESSION['ul_truefalse'] = false;
}
}
echo "Player " . $_SESSION['turn'] . ", it's your turn!";
echo $this_happened;
?>
<table border="1" width="40%">
<tr>
<td><?php echo $_SESSION['ul_display'] ?></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
Related
This question already exists:
Why does the hash function not work no matter where i put it? [closed]
Closed 1 year ago.
I´m trying to get this form right but i can´t seem to find out whats wrong.
No matter where i put the hash in the code i can´t seem to get it to work.
I tried to get the input out from the form to convert it to a hash with password_hash(#psw, PASSWORD_DEFAULT) but no matter where i put it it won´t work.... do i need to say i am a newbie at this =)
if(isset($_POST["uname"]) && isset($_POST["psw"]))
{
// check if user exist.
$file=fopen("log.txt","r");
$finduser = false;
while(!feof($file))
{
$line = fgets($file);
$array = explode(";",$line);
if(trim($array[0]) == $_POST['uname'])
{
$finduser=true;
break;
}
}
fclose($file);
// register user
if( $finduser )
{
echo $_POST["uname"];
echo ' fanns redan registrerad!';
}
else
{
$file = fopen("log.txt", "a");
//funkar ej
$psw = password_hash($_POST['psw'], PASSWORD_DEFAULT);//funkar ej
fputs($file,$_POST["uname"].";".$_POST["psw"]."\r\n");
fclose($file);
echo $_POST["uname"];
echo " är nu registrerad!";
}
}
if(isset($_POST['login'])) // it checks whether the user clicked login button or not
{
$uname = $_POST['uname'];
$psw = $_POST['psw'];
if(isset($_POST["uname"]) && isset($_POST["psw"])){
$file = fopen('log.txt', 'r');
$good=false;
while(!feof($file)){
$line = fgets($file);
$array = explode(";",$line);
if(trim($array[0]) == $_POST['uname'] && trim($array[1]) == $_POST['psw']){
$good=true;
header("Location:index.php");
break;
}else{
echo "Ogiltigt användarnamn eller lösenord";
}
}
fclose($file);
}
}
?>
<html>
<head>
<title> Registreringssida </title>
</head>
<body>
<form action="" method="post">
<table width="200" border="0">
<tr>
<td>Användarnamn:</td>
<td> <input type="text" name="uname" > </td>
</tr>
<tr>
<td>Lösenord:</td>
<td><input type="password" name="psw"></td>
</tr>
<tr>
<td> <input type="submit" name="reg" value="Ny Användare"></td>
<td></td>
</tr>
</table>
</form>
<form action="" method="post">
<table width="200" border="0">
<tr>
<td>Användarnamn:</td>
<td> <input type="text" name="uname" > </td>
</tr>
<tr>
<td>Lösenord:</td>
<td><input type="password" name="psw"></td>
</tr>
<tr>
<td> <input type="submit" name="login" value="Logga In"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>```
I have a form tag in which I have an input name and on click of a button, the value is displayed in table form. Now I want to update that value. How do I do it? This code does not have any database.
<form>
<input type="text" name="fname" value="" />
<input type="submit" value="submit" name="btn_submit" />
</form>
<br>
<br>
<table border="1">
<th>Name</th>
<th>Delete</th>
<th>Update</th>
<?php
session_start();
$na = array();
if (isset($_GET['btn_submit']))
{
if (isset($_SESSION['name']))
{
$na = $_SESSION['name'];
}
$na[] = $_GET['fname'];
$_SESSION['name'] = $na;
for ($i = 0; $i < count($na); $i++) {
?>
<tr>
<td><?php echo $na[$i]; ?></td>
<td>DELETE</td>
<?php
if(isset($_GET['del']))
{
}
?>
<td>UPDATE</td>
</tr>
<?php
}
}
?>
Below is the code I have, which checks for if text box is empty then give warning beside text box once clicked on Submit.
<?php
if(isset($_POST["submit"])) {
$fqdn = $_POST["fqdn"];
$ip = $_POST["ip"];
$fileText = $fqdn."\n".$ip;
$file = fopen("inputFile.txt","w");
fwrite($file, $fileText);
fclose($file);
}
?>
<form action = "<?php $_PHP_SELF ?>" method = "post">
<table style= "width:400px">
<tr class="spaceUnder">
<td><b>FQDN:</b></td>
<td><input type="text" name="fqdn" placeholder="server.domain.com"/></td>
<td> <?php if(isset($_POST['fqdn']) && $_POST['fqdn'] == ''){ echo "<font color='red'>FQDN cannot be empty</font>";} ?> </td>
</tr>
<tr class="spaceUnder">
<td><b>IP:</b></td>
<td><input type="text" name="ip" placeholder="***.***.***.***"/></td>
<td> <?php if(isset($_POST['ip']) && $_POST['ip'] == ''){ echo "<font color='red'>IP cannot be empty</font>"; } ?> </td>
</tr>
<tr>
<td align="center" colspan="2">
<input type = "submit" name="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
After clicking on submit, the php is still going and writing to the file. If i give exit() or return false; at the below step:
<td> <?php if(isset($_POST['fqdn']) && $_POST['fqdn'] == ''){ echo "<font color='red'>FQDN cannot be empty</font>"; exit();} ?> </td>
the form becomes incomplete, means, the IP textbox and submit button will not exist. Any way to make it right?
So what we have here. We are making 2 variables that will dispay our errors. The variable in first place are emty because we dont know what we have post. After we post the data we can see if the post is emty or not. If the post is emty we assign an error message to the variable and dispay it to our table.
$error_FQDN = "";
$error_ip = "";
if(isset($_POST["submit"])) {
if($_POST["fqdn"] == "" || $_POST["ip"] == ""){
if($_POST["fqdn"] == ""){
$error_FQDN = "FQDN cannot be empty!";
}
if($_POST["ip"] == ""){
$error_ip = "IP cannot be empty!";
}
} else {
$fqdn = $_POST["fqdn"];
$ip = $_POST["ip"];
$fileText = $fqdn."\n".$ip;
$file = fopen("inputFile.txt","w");
fwrite($file, $fileText);
fclose($file);
}
}
<form action = "<?php $_PHP_SELF ?>" method = "post">
<table style= "width:400px">
<tr class="spaceUnder">
<td><b>FQDN:</b></td>
<td><input type="text" name="fqdn" placeholder="server.domain.com"/></td>
<td><?php echo $error_FQDN ?></td>
</tr>
<tr class="spaceUnder">
<td><b>IP:</b></td>
<td><input type="text" name="ip" placeholder="***.***.***.***"/></td>
<td><?php echo $error_ip ?></td>
</tr>
<tr>
<td align="center" colspan="2">
<input type = "submit" name="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
Try this,
// Check for form submit and if fields aren't empty
if(isset($_POST["submit"]) && $_POST['fqdn'] != "" && $_POST['ip'] != "") {
$fqdn = $_POST["fqdn"];
$ip = $_POST["ip"];
$fileText = $fqdn."\n".$ip;
$file = fopen("inputFile.txt","w");
fwrite($file, $fileText);
fclose($file);
}
By validating fqdn and ip, if values aren't empty, if case will be executed. Else it simply won't run.
I'm trying to teach myself php and mysql and I'm having trouble with a form I'm working on for a football pool I'm trying to put together. I'm looking for a little help on the best way to submit the data from this form. The form gets data from my database and repeats for the appropriate number of rows. Upon submitting the form each row should be inserted or updated to the database. The data that needs to be submitted is: userid, gameid, pick, and tbPoints.
The form is a little rough as I have not finished it yet. I just cant seem to get the form to submit each row as a new entry to the database, it only submits the last game. I know I have a problem with the loop to submit, but I just can't seem to figure out how to get it. Any help is appreciated!
here is my form:
<?php require_once('Connections/t2016.php'); ?>
<?php
mysql_select_db($database_t2016, $t2016);
$query_gamedays = "SELECT DISTINCT schedule.weekDay, schedule.`date` FROM schedule WHERE schedule.weekNum=1";
$gamedays = mysql_query($query_gamedays, $t2016) or die(mysql_error());
$row_gamedays = mysql_fetch_assoc($gamedays);
$totalRows_gamedays = mysql_num_rows($gamedays);
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post" name="form1">
<table border="2" cellpadding="3" cellspacing="2">
<tr align="center">
<td>Time</td>
<td colspan="3">Matchup</td>
<td>Current Pick</td>
</tr>
<?php do {
$day = $row_gamedays['weekDay'];
$date = $row_gamedays['date'];
?>
<tr wrap="nowrap">
<td colspan="5"><?php echo '<strong>'.$day.'</strong>, '.$date; ?></td>
</tr>
<?php
mysql_select_db($database_t2016, $t2016);
$query_sched = "SELECT * FROM schedule WHERE schedule.weekNum=1 AND schedule.weekDay='$day'";
$sched = mysql_query($query_sched, $t2016) or die(mysql_error());
$row_sched = mysql_fetch_assoc($sched);
$totalRows_sched = mysql_num_rows($sched);
?>
<?php do {
$gameid = $row_sched['gameID'];
$time = $row_sched['time'];
$vteam = $row_sched['visitorID'];
$hteam = $row_sched['homeID'];
mysql_select_db($database_t2016, $t2016);
$query_picks = "SELECT * FROM picks WHERE picks.gameID=$gameid AND picks.userID=1";
$picks = mysql_query($query_picks, $t2016) or die(mysql_error());
$row_picks = mysql_fetch_assoc($picks);
$totalRows_picks = mysql_num_rows($picks);
if($totalRows_picks > 0) {
$pick = $row_picks['pickID'];
$tbp = $row_picks['tiebreakerPoints'];
} else {
$pick = 'No Pick';
$tbp = '0';
}
$vp = '';
$hp = '';
if($pick == $vteam) {
$vp = 'checked';
} elseif($pick == $hteam) {
$hp = 'checked';
}
?>
<tr align="center">
<td><?php echo $time; ?></td>
<td align="right"><?php echo $vteam.'<input type="radio" name="pickID'.$gameid.'[]" value="'.$vteam.'" '.$vp.'>'; ?></td>
<td align="center"> # </td>
<td align="left"><?php echo '<input type="radio" name="pickID'.$gameid.'[]" value="'.$hteam.'" '.$hp.'>'.$hteam; ?></td>
<td><?php echo $pick; ?></td>
</tr>
<?php if($row_sched['is_tiebreaker'] > 0) { ?>
<tr>
<td colspan="4" align="right" wrap="nowrap"><?php echo 'Enter Tiebreaker Points: <input type="number" name="tbpoints[]" min="0" value="'.$tbp.'">'; ?></td>
<td align="center"><?php echo $tbp; ?></td>
</tr>
<?php } ?>
<input type="hidden" name="gameID[]" value="$gameid">
<input type="hidden" name="userID" value="1">
<?php } while ($row_sched = mysql_fetch_assoc($sched)); ?>
<tr>
<?php } while ($row_gamedays = mysql_fetch_assoc($gamedays)); ?>
<td colspan="5" align="right" wrap="nowrap">
<input type="submit" name"submit" value="Submit Picks">
</td>
</tr>
</table>
</form>
<p> </p>
</body>
</html>
<?php
mysql_free_result($sched);
mysql_free_result($picks);
mysql_free_result($gamedays);
?>
again, the form is really rough so please be kind. Thanks for the help
You just loop through these values like a normal array.
$gameID = $_POST['gameID'];
for($x=0; $x<count($gameID); $x++ ) { .... }
As for the radio buttons/check boxes - you need to give each group a unique name. The only thing to remember with these controls is that if that are not set then nothing is submitted to the server. You need to check if they are part of the post values i.e.
if( isset( $_POST['cbPoints'] ) ) { do something }
Otherwise you'll get errors when trying to access them.
I am working on an assignment for my PHP1 Class and we are working on sticky forms, my assignment is to write an order form that validates that both a name is entered and a phone model is selected and if both are filled posts that data back to the page and if one or both is missing an error message is posted back to the page. Accessories are Optional. Currently the script will post an error if no phone is selected and a name is input into the form, it will post an error if both are missing, but if a name is missing and a phone is selected then it will not flag as an error and continue processing the script back to the page. I attempted to right a function to validate that both the userName text field AND a phones radio button are selected to be true or if false then the error message is presented. Can anyone tell me why my form is processing the data when only a phone model is selected and the name field is blank?
Script(OrderForm):
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
</head>
<body>
<h1>Order Your Smartphone</h1>
<?php
/**
* Created by PhpStorm.
* User: Daniel Vermillion
* Date: 10/27/2014
* Time: 7:59 PM
*/
$isValid = false;
//function totalAcc() {
// foreach($_POST['acc'] as $item) {
// $accPrice[] = $item;
// }
// array_sum($accPrice);
// return $accPrice;
//}
//function totalCost() {
// $subtotal = $phonePrice + $accPrice;
// $tax = 0.08;
// $taxTotal = $subtotal * $tax;
// $total = $subtotal + $taxTotal;
// return $subtotal;
// return $taxTotal;
// return $total;
//}
function validData() {
if(isset($_POST['userName']) && isset($_POST['phones'])) {
return true;
}
else {
return false;
}
}
function calcResults() {
$isValid = validData();
if($isValid) {
echo "Full Name: {$_POST['userName']} <br />";
echo "Phone Model: {$_POST['phones']} <br />";
echo "Accessories: {$_POST['acc']} <br />";
// echo "Subtotal: $subtotal <br />";
// echo "Tax: '$taxTotal' <br />";
// echo "Total Cost: $total <br />";
}
else {
echo "Please enter your name and select a phone model.";
}
}
?>
<form method="post" action="index.php">
Full Name: <input type="text" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>" /><br />
<h4>Add Smartphone</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Phone</td>
<td>Model</td>
<td>Storage</td>
<td>Price</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP8") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP8</td>
<td>8 GB</td>
<td>$400</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP16") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP16</td>
<td>16 GB</td>
<td>$450</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP8") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP8</td>
<td>8 GB</td>
<td>$500</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP16") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP16</td>
<td>16 GB</td>
<td>$550</td>
</tr>
</table>
<h4>Add Accessories</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Accessory</td>
<td>Price</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="handstrap" <?php if(isset($_POST['acc']) && in_array('handstrap', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Hand Strap</td>
<td>$6.25</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="leathercase" <?php if(isset($_POST['acc']) && in_array('leathercase', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Leather Case</td>
<td>$14.50</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="headphones" <?php if(isset($_POST['acc']) && in_array('headphones', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Headphones</td>
<td>$18.75</td>
</tr>
</table>
<br />
<input type="submit" name="submit" value="Click to Finalize Order" /><br /><br />
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
calcResults();
}
?>
</body>
</html>
isset() for strings returns true for an empty string.
https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
Try Empty()
edit: please note that if the field has a space in it, it will not be counted as empty. You should probably use Trim() on the result to ensure that there is no whitespace.
You need to echo the result..
replace
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
calcResults();
}
with
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo calcResults();
}
UPDATE:
<!DOCTYPE html>
<html>
<head>
<title>Order Form</title>
</head>
<body>
<h1>Order Your Smartphone</h1>
<?php
/**
* Created by PhpStorm.
* User: Daniel Vermillion
* Date: 10/27/2014
* Time: 7:59 PM
*/
$isValid = false;
//function totalAcc() {
// foreach($_POST['acc'] as $item) {
// $accPrice[] = $item;
// }
// array_sum($accPrice);
// return $accPrice;
//}
//function totalCost() {
// $subtotal = $phonePrice + $accPrice;
// $tax = 0.08;
// $taxTotal = $subtotal * $tax;
// $total = $subtotal + $taxTotal;
// return $subtotal;
// return $taxTotal;
// return $total;
//}
function validData() {
if(isset($_POST['userName']) && !empty($_POST['userName'])) {
if(isset($_POST['phones']) && !empty($_POST['phones'])) {
$acc = (isset($_POST['acc']) && !empty($_POST['acc'])) ? " <br />Accessories: " . implode(" and ",$_POST['acc']) . " <br />" : "";
return "Full Name: " . $_POST['userName'] . " <br />Phone Model: " . $_POST['phones'] . $acc;
} else {
return "Please enter the phone model.";
}
} else {
return "Please enter your name and select a phone model.";
}
}
function calcResults() {
$isValid = validData();
return $isValid;
}
?>
<form method="post" action="form.php">
Full Name: <input type="text" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>" /><br />
<h4>Add Smartphone</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Phone</td>
<td>Model</td>
<td>Storage</td>
<td>Price</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP8") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP8</td>
<td>8 GB</td>
<td>$400</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="SP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "SP16") echo 'checked'; ?> /></td>
<td>SuperPhone</td>
<td>SP16</td>
<td>16 GB</td>
<td>$450</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP8" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP8") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP8</td>
<td>8 GB</td>
<td>$500</td>
</tr>
<tr>
<td><input type="radio" name="phones" value="MP16" <?php if(isset($_POST['phones']) && $_POST['phones'] == "MP16") echo 'checked'; ?> /></td>
<td>MegaPhone</td>
<td>MP16</td>
<td>16 GB</td>
<td>$550</td>
</tr>
</table>
<h4>Add Accessories</h4>
<table cellspacing="4" cellpadding="4" border="1">
<tr>
<td></td>
<td>Accessory</td>
<td>Price</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="handstrap" <?php if(isset($_POST['acc']) && in_array('handstrap', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Hand Strap</td>
<td>$6.25</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="leathercase" <?php if(isset($_POST['acc']) && in_array('leathercase', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Leather Case</td>
<td>$14.50</td>
</tr>
<tr>
<td><input type="checkbox" name="acc[]" value="headphones" <?php if(isset($_POST['acc']) && in_array('headphones', $_POST['acc'])) echo ' checked'; ?> /></td>
<td>Headphones</td>
<td>$18.75</td>
</tr>
</table>
<br />
<input type="submit" name="submit" value="Click to Finalize Order" /><br /><br />
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo calcResults();
}
?>
</body>
</html>