This is similar to a previous question I asked about matching the selected radio button with the value in the input field.
The code lets a user build a quiz by entering a question and 4 possible answers. You must select one of the answers as the correct one and on a separate PHP page, the answers must be displayed with the correct one in green. Originally this problem was solved, but after I modified the code for validation, the original loop for display would not work.
Here is the output of the code:
I need Albany to print in green since it's the correct answer and was selected with the radio button.
Here is my code for the form:
<?php
session_start();
// Define variables and set to empty values
$questionErr = $answer0Err = $answer1Err = $answer2Err = $answer3Err = "";
$question = $answer0 = $answer1 = $answer2 = $answer3 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$valid = True;
if (empty($_POST['question'])) {
$questionErr = "Please supply a question";
$valid = False;
} else {
$question = test_input($_POST['question']);
$_SESSION['question'] = $_POST['question'];
}
if (empty($_POST['answer0'])) {
$answer0Err = "Please supply a possible answer";
$valid = False;
} else {
$answer0 = test_input($_POST['answer0']);
$_SESSION['answer0'] = $_POST['answer0'];
}
if (empty($_POST['answer1'])) {
$answer1Err = "Please supply a possible answer";
$valid = False;
} else {
$answer1 = test_input($_POST['answer1']);
$_SESSION['answer1'] = $_POST['answer1'];
}
if (empty($_POST['answer2'])) {
$answer2Err = "Please supply a possible answer";
$valid = False;
} else {
$answer2 = test_input($_POST['answer2']);
$_SESSION['answer2'] = $_POST['answer2'];
}
if (empty($_POST['answer3'])) {
$answer3Err = "Please supply a possible answer";
$valid = False;
} else {
$answer3 = test_input($_POST['answer3']);
$_SESSION['answer3'] = $_POST['answer3'];
}
}
// Function to sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// If valid, send to QuestionReview.php to display answers
if ($valid) {
$_SESSION['radio'] = $_POST['radio'];
header('location: QuestionReview.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User-Created Quiz</title>
<style>
.shadow {
-webkit-box-shadow: 3px 3px 5px 6px #ccc; /* Safari 3-4, iOS 4.0.2 - 4.2, Android 2.3+ */
-moz-box-shadow: 3px 3px 5px 6px #ccc; /* Firefox 3.5 - 3.6 */
box-shadow: 3px 3px 5px 6px #ccc; /* Opera 10.5, IE 9, Firefox 4+, Chrome 6+, iOS 5 */
}
.instructions {
color: #696D6E;
}
#form-background {
background-color: #ECEDE8;
}
.error {
color: red;
}
</style>
</head>
<body>
<div style="width:600px">
<fieldset id="form-background" class="shadow">
<h1 class="instructions" style="text-align:center">User-Created Quiz</h1>
<p class="instructions" style="text-align:center">
<strong>Please enter a question of your own,
along with 4 possible answers in the
form below. Be sure to select the
correct answer to your question
before submitting the form.</strong>
</p>
<form style="text-align:center;" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br>
<label class="instructions" for="question" >Enter your question here</label><br>
<input type="text" name="question" size="50" value='<?php echo $question;?>' />
<span class="error">* <br /><?php echo $questionErr; ?></span>
<br><br>
<p class="instructions">
Please provide four answers to your question and select the
correct one.
</p>
<input type="radio" name="radio" value="answer0">
<input type="text" name="answer0" value="<?php echo $answer0; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer0Err; ?></span>
<br><br>
<input type="radio" name="radio" value="answer1">
<input type="text" name="answer1" value="<?php echo $answer1; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer1Err; ?></span>
<br><br>
<input type="radio" name="radio" value="answer2">
<input type="text" name="answer2" value="<?php echo $answer2; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer2Err; ?></span>
<br><br>
<input type="radio" name="radio" value="answer3">
<input type="text" name="answer3" value="<?php echo $answer3; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer3Err; ?></span>
<br><br>
<input type="submit" value="Submit Entry">
</form>
</fieldset>
</div>
</body>
</html>
And here is my code for the result page:
<?php
session_start();
// Pull all variables from SESSION
$question = $_SESSION['question'];
$answer0 = $_SESSION['answer0'];
$answer1 = $_SESSION['answer1'];
$answer2 = $_SESSION['answer2'];
$answer3 = $_SESSION['answer3'];
$radio = $_SESSION['radio'];
$answerArray = array($answer0, $answer1, $answer2, $answer3);
shuffle($answerArray);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Entry Review</title>
<style>
.instructions {
color: #696D6E;
}
</style>
</head>
<body>
<h1 class="instructions">Entry Review</h1>
<p><em>You entered the following question:</em></p>
<p><strong><?php echo $question; ?></strong></p><br>
<p><em>These are the answers you provided:</em>
<p>
<strong>
<?php
if(isset($_SESSION['radio'])) {
$radio = $_SESSION['radio'];
foreach ($answerArray as $value) {
echo $value . "<br />";
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
?>
</strong>
</p>
</body>
</html>
Get a bit of A4 plain paper, work away from your computer for ten minutes.
Now, establish what you're trying to achieve in blocks, what do you want each part of your skillset/language/operator-syntax (PHP, javascript, CSS, HTML etc.) to do?
You have a list of outputs already displayed on your project and you want to mark a chosen output, as differet from the others.
work backwards from that end result, what will make this change? That's right, CSS, so you can write on your paper, you need a CSS class (or other identifier) for a chosen output, that you can call for that answer.
So how will the CSS know which output to choose? Where is this data held?
This data appears to be in PHP somewhere, (but it's not immediately obvious from your code). So, you need a PHP IF statement to check If the answer that is being displayed to the browser is the answer that the user has chosen then that answer needs to be encased in a CSS class somehow (<div> or <span> ) to effect the dfference in appearance.
And that's it. You should have enough of a structure now to go away and to write out notes on that A4 sheet and then use those notes to break your various issues down into component parts (here, there are parts for difining what behaviour should happen and then parts for making that behaviour happen).
Rewrite your code in 5-10 minutes you'll have it exactly as you want it.
On QuestionReview.php page, get the correct answer like this,
$correct_answer = $_SESSION[$_SESSION['radio']];
So keep your quiz page as it is and after submitting, process your form like this:
QuestionReview.php:
<?php
session_start();
// Pull all variables from SESSION
$question = $_SESSION['question'];
$answer0 = $_SESSION['answer0'];
$answer1 = $_SESSION['answer1'];
$answer2 = $_SESSION['answer2'];
$answer3 = $_SESSION['answer3'];
$correct_answer = $_SESSION[$_SESSION['radio']];
$answerArray = array($answer0, $answer1, $answer2, $answer3);
shuffle($answerArray);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Entry Review</title>
<style>
.instructions {
color: #696D6E;
}
</style>
</head>
<body>
<h1 class="instructions">Entry Review</h1>
<p><em>You entered the following question:</em></p>
<p><strong><?php echo $question; ?></strong></p><br>
<p><em>These are the answers you provided:</em>
<p>
<strong>
<?php
if(isset($_SESSION['radio'])) {
foreach ($answerArray as $value) {
$output = "<span";
if($value == $correct_answer){
$output .= " class='instructions'";
}
$output .= ">" . $value . "</span><br />";
echo $output;
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
?>
</strong>
</p>
</body>
</html>
In each iteration of the foreach loop, check if the current option equals to the correct answer or not. If it is then apply the class instructions to the current option.
Output: (Screenshot)
You are almost there... just make it simple:
If you have:
$question = $_SESSION['question'];
$radio = $_SESSION['radio'];
$answerArray = [$_SESSION['answer0'], $_SESSION['answer1'], $_SESSION['answer2'], $_SESSION['answer3']];
Then you can:
if(isset($_SESSION['radio'])) {
foreach ($answerArray as $value) {
echo $_SESSION['radio'] == $value ? "<span style=\"color:green\">Make $value green.</span><br />" : "<span style=\"color:#666\">Make $value grey or red.</span><br />";
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
Which equals to:
if(isset($_SESSION['radio'])) {
foreach ($answerArray as $value) {
if ($_SESSION['radio'] == $value){
echo "<span style=\"color:green\">Make $value green.</span><br />";
} else {
echo "<span style=\"color:#666\">Make $value grey or red.</span><br />";
}
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
Related
I am making a PHP project and am trying to change an input boxes value according to a PHP variable, how would I do this? So far, when I try to change the input boxes value it just changes the value to the name of the variable.
Here's the html for that section:
echo '
<html>
<title>Ramen</title>
<body>
<h1>
<p>Welcome to NoteBook!</p>
<form method="post">
<p>File Name:<input type="text" name="fname"></p>
<p>Type Here:<input type="text" name="content" id="TextBox" value="<?php echo $value; ?>"><p>
<p>Save:<input type="submit" value="Save"></p>
</form>
<form method="post">
<p>File to Open: <input type="text" name="filename"></p>
<input type="submit" value="Open">
</form>
</h1>
</body>
<style>
body{
background-color:#66b3ff;
}
p{
margin-left:30px;
}
h1{
background-color:white;
height:600px;
border-radius:1px;
font-size:18px;
font:italic;
}
#TextBox{
height:500;
width:700;
}
{
</style>
</html>```
$value doesn't appear to be being set anywhere.
I'm also a little confused as to why you have two <form>s.
As a starter, you need to parse the values coming in from the form, for example:
<?php
if (isset($_POST["filename"]) { // The $_POST variables are set using the name element of the <input> tag
$value = $_POST["filename"]
}
?>
You would likely want to do some more validation on the content of $_POST["value"] before accepting it.
Perhaps take a look at this example to get you started.
I leave you a possible example with explanation.
Besides, I have adapted the HTML structure a bit, since it has serious formatting problems. I advise you to read the manual on how to use the labels.
I added the name attribute to the submit, in order to know if the form is defined:
<input type="submit" name="save_data" value="Save">
Example:
<?php
// reset ¡important! (avoid warning <b>Warning</b>: Undefined variable etc..)
$file_name = $content = $txt_content = '';
// Recomended to check if the form is define
if (isset($_POST['save_data'])) {
// Get the inputs data
$file_name = $_POST['fname'] ?? '';
$content = $_POST['content'] ?? '';
// You can use textarea
$txt_content = $_POST['txt_content'] ?? '';
// Data is true
if ($file_name && $content && $txt_content) :
// Do somenting (ex: save it in DB)
//
//
$success = "Save correctly: $file_name";
// Data is empty (optional)
else :
$error = 'Te fields are empty.';
endif;
}
?>
<html lang="en-EN">
<head>
<title>Ramen</title>
<style>
body{
background-color:#66b3ff;
}
p {
margin-left:30px;
}
.wrapper {
background-color:white;
height:600px;
border-radius:1px;
font-size: 1rem;
font:italic;
padding: 1rem;
}
textarea {
height:200px;
width:400px;
}
.error {
color: red;
}
.success {
color: green;
}
</style>
</head>
<body>
<div class="wrapper">
<h1>Welcome to NoteBook!</h1>
<form method="post">
<lable for="fname">File Name:</lable>
<input type="text" name="fname" id="fname" value="<?php echo $file_name; ?>"></p>
<label for="content">Type Here:</label>
<input type="text" name="content" id="content" value="<?php echo $content; ?>">
<!-- for the content you could use the textarea tag -->
<textarea name="txt_content"><?php echo $txt_content; ?></textarea>
<input type="submit" name="save_data" value="Save">
<?php if (isset($error)) echo '<p class="error">' . $error . '</p>'; ?>
<?php if (isset($success)) echo '<p class="success">' . $success . '</p>'; ?>
</form>
</div>
</body>
</html>
I'm relatively new to the web development scene and have been assigned with creating a website capable of logging calls.
I have used a HTML form to achieve this - I have made many of these in the past, but have never encountered this issue before.
My page contains 3 buttons: one to log a call, one to forward a call, and one to view all call logs. I achieve this by using an onclick method in the buttons:
<button type=submit value=log onclick="window.location.href='reception.php?log=1';">Log a call.</button>
And then using PHP GET to display the appropriate content on the rest of the page.
try {
$log = $_GET["log"];
}
catch(Exception $ex) {
die();
}
if($log) {
?>
// create form
This works perfectly, and I have created my form as below.
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" name="log">
<p>
<label>Call date: </label>
<input type="date" name="date" value=<?php echo date("Y-m-d"); ?>>
<span class="error"><sup> <?php echo $dateErr; ?></sup></span>
</p>
<br>
<p>
<label>Does the client have a contract?</label>
<select name="contract">
<option value="default" selected disabled>Please select...</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
<span class="error"><sup> <?php echo $contractErr; ?></sup></span>
</p>
<br>
<p>
<label>Client forename:</label>
<input type=text name="fname" <?php if(isset($fname)) echo "value='".$fname."'";?>>
<span class="error"><sup> <?php echo $fnameErr; ?></sup></span>
</p>
<br>
<p>
<label>Client surname:</label>
<input type=text name="sname">
<span class="error"><sup> <?php echo $snameErr; ?></sup></span>
</p>
<br>
<p>
<label style="position: relative; top: -135px;">Client enquiry:</label>
<textarea name=enq style="font-size: 14px; height: 150px; width: 300px;"></textarea>
<span class="error"><sup> <?php echo $enqErr; ?></sup></span>
</p>
<br>
<p>
<button type=submit name=submit value=submit style="position:relative; right: -115px; height:40px; width: 100px;">Submit</button>
</p>
It works just fine. However, the issue comes when submitting the form: for some reason, all PHP variables that I define come up empty when submit is clicked, meaning that any auto-completion / error messages do not show up. As you can see in my form code, as a test I made it autofill the "fname" field if the user has already set it, but it does not work.
Here is my PHP for validation (it is not complete yet, I just wanted to do all of the 'isset' checks first):
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["submit"])) {
$go = true;
$query = "INSERT INTO callLog VALUES(NULL, '";
if(empty($_POST["date"])) {
$dateErr = "* Please enter a date.";
$go = false;
}
else {
$query .= date('Y-m-d', strtotime($_POST["date"]))."', ";
}
if(empty($_POST["contract"])) {
$contractErr = "* Please select 'Yes' or 'No'.";
$go = false;
}
else {
$contract = test_input($_POST["contract"]);
if($contract == "Yes") {
$contract = "TRUE";
}
else {
$contract = "FALSE";
}
$query .= $contract.", '";
}
if(empty($_POST["fname"])) {
$fnameErr = "* Please enter a forename.";
$go = false;
}
else {
$fname = test_input($_POST["fname"]);
$query .= $fname."', '";
}
if(empty($_POST["sname"])) {
$snameErr = "* Please enter a surname.";
$go = false;
}
else {
$sname = test_input($_POST["sname"]);
$query .= $fname."', '";
}
if(empty($_POST["enq"])) {
$enqErr = "* Please enter an enquiry.";
$go = false;
}
else {
$query .= $enq."');";
}
if($go) {
$conn->query($query);
header('Location: reception.php');
}
?><script>
$(document).ready(function() {
window.location.href='reception.php?log=1';
});
</script><?php
}
}
The JS at the end is simply so that the page redirects to the call log form page once the data has been submitted, rather than having to click the 'call log' button again.
I'm completely at a loss as to why this doesn't work. Aside from the 'GET' method to display the page, I've done everything as I have in the past which has worked fine. Is it the 'GET' method interfering, or am I missing something?
I have seen that potentially trying something such as Ajax to handle the submission to see if it will work is a possibility, but I am not too familiar with JQuery (knowing only the basics) and do not know how to work with Ajax.
Thanks!
You're highjacking the form submission. You're onclick="window.location.href='reception.php?log=1';" just makes a GET request to that page, not a POST to your form action.
Currently I am sending error messages and storing the value of my input fields in sessions.
Form example
<label class="errormsg"><?php echo $_SESSION['msgProductPrice']; unset($_SESSION['msgProductPrice']); ?></label>
<input type="text" name="product_price" value="<?php echo $_SESSION['val_ProductPrice']; unset($_SESSION['val_ProductPrice']); ?>" />
PHP
$Price = $_POST['product_price'];
$errorcount = 0;
if(empty($Price) === true){
$PriceErrormsg = "empty";
$errorcount++;
}
if($errorcount === 0) {
// success
} else {
$_SESSION['val_ProductPrice'] = $Price;
$_SESSION['msgProductPrice'] = $PriceErrormsg;
}
This works perfectly with one of a kind input field. If I try with multiple input fields with the same name, it doesn't work.
Form example
<label class="errormsg"><?php echo $_SESSION['msgProductAmount']; unset($_SESSION['msgProductAmount']); ?></label>
<input type="text" name="product_amount[]" value="<?php echo $_SESSION['val_ProductAmount']; unset($_SESSION['val_ProductAmount']); ?>" />
<label class="errormsg"><?php echo $_SESSION['msgProductAmount']; unset($_SESSION['msgProductAmount']); ?></label>
<input type="text" name="product_amount[]" value="<?php echo $_SESSION['val_ProductAmount']; unset($_SESSION['val_ProductAmount']); ?>" />
This is where I'm unsure on how to validate all the input fields, how to keep the value in each input field when you hit submit and how to send an errormsg about each field?
PHP
$Amount= $_POST['product_amount'];
$errorcount = 0;
if(empty($Amount) === true){
$AmountErrormsg = "empty";
$errorcount++;
}
if($errorcount === 0) {
// success
} else {
$_SESSION['val_ProductAmount'] = $Amount;
$_SESSION['msgProductAmount'] = $AmountErrormsg;
}
If I understand your problem, multiple product amounts are being submitted, and you want to validate each one individually and display the error message next to the appropriate textbox?
Because you are receiving an array of values, you need to create a corresponding array of error messages.
It's a while since I've done any PHP, so this might not be 100% correct, but I think you need something along these lines...
$AmountErrorMessage = Array();
foreach ($Amount as $key => $value) {
if (empty($value)) {
$AmountErrorMessage[$key] = 'empty';
}
}
if ($AmountErrorMessage->count() > 0) {
// success
} else {
$_SESSION['val_ProductAmount'] = $Amount;
$_SESSION['msgProductAmount'] = $AmountErrorMessage;
}
You would then also need to iterate through the array in order to generate the HTML for your form, creating a label and input box for each value submitted.
This code help you to do it as per your wish..
<?php
session_start();
?>
<html>
<head>
<title></title>
<style>
.errormsg{
color:red;
}
</style>
</head>
<body>
<?php
if(isset($_POST['product_amount']))
{
$errorcount = 0;
for($i=0;$i<count($_POST['product_amount']);$i++){
$Amount[$i] = $_POST['product_amount'][$i];
if(empty($Amount[$i]) === true){
$_SESSION['msgProductAmount'][$i] = "empty";
$errorcount++;
}
else
$_SESSION['val_ProductAmount'][$i] = $Amount[$i];
}
if($errorcount === 0) {
unset($_SESSION['msgProductAmount']);
echo "success";
}
}
?>
<form action="" method="POST">
<?php
$cnt = 10;
for($i=0;$i<$cnt;$i++){
?>
<input type="text" name="product_amount[<?=$i?>]" value="<?php echo isset($_SESSION['val_ProductAmount'][$i]) ? $_SESSION['val_ProductAmount'][$i] : '';?>" />
<label class="errormsg"><?php echo $res = isset($_SESSION['msgProductAmount'][$i]) ? $_SESSION['msgProductAmount'][$i] : '' ; ?></label>
<br/>
<?php
}
?>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
<?php
unset($_SESSION['msgProductAmount'],$_SESSION['val_ProductAmount']);
?>
For some reason, my code is only outputting 'p3' and 'p4' twice. I was wondering if anyone could point out why it's repeating, and it'd be appreciated. Here's an example of what is wrong (this only is on p3 and p4 as stated above, p1 and p2 work fine)
http://i.imgur.com/glNXwr7.png
Here's my code:
index.php -
<?php
session_start();
if (!isset($_SESSION['p']))
{
$_SESSION['p'] = 'p1';
}
include('core.php');
include('core2.php');
$story = new Story;
$action = new Action;
$part = $_SESSION['p'];
?>
<!DOCTYPE HTML>
<html>
<head>
<title>MacBeth Console</title>
<style>
body{
background:black;
color:#2ecc71;
font-family: "Courier New", Courier, monospace
}
.txt{
border:0px;
background-color:black;
color:#2ecc71;
font-family: "Courier New", Courier, monospace
}
input:focus {outline: none; }
</style>
</head>
<body>
<?php
echo 'DEBUG: P_'.$part.' <br />';
if ($_SESSION['p'] == 'p1')
$story->p1();
else
$action->continueStory($part, '');
if (isset($_POST['submit']))
{
$action->ContinueStory($part, $_POST['yourAction']);
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="p" value="<?php echo $part; ?>" style="vertical-align:middle;">
<img src="cmd.png"><input type="text" id="input" name="yourAction" class="txt">
<input type="submit" name="submit" value="continue">
</form>
</body>
</html>
core.php -
<?php
class Story
{
public function p1()
{
print '<b>Witch 1</b>: When shall we all meet again? <br />
<b>Witch 2</b>: When the hurly-burly is done, and the battle\'s lost and won. <br />
<b>Witch 3</b>: That will be ere the set of sun. <br />
<b>Witch 1</b>: Where\'s the place? <br />
<b>Witch 2</b>: Upon the heath, is this location to thou satisfaction? <br />';
}
public function p2($action)
{
$action = strtolower($action);
if ($action == 'yes')
{
$_SESSION['p'] = 'p3';
print '** The meeting shall be held upon the heath to meet with MacBeth. ** -- PRESS ENTER';
}
else if ($action == 'no')
{
$_SESSION['p'] = 'p3';
print '** Despite your opinion, the other witches decide the best place to meet would be at the heath. **';
}
else
{
print 'Unknown action "'.$action.'".';
}
}
public function p3($action)
{
echo 'test ';
$_SESSION['p'] = 'p4';
/*return '<b><i>Scene II</i></b> <br />
<b>Duncan</b>: What bloody man is that? He can report, as seemeth by his plight, of the revolt the newest state. <br /> <br />
<b>Sergent</b>: Doubtful it stood; As two spent swimmers, that do cling together, and choke their art. The merciless Macdonwald-- Worthy to be a rebel, for to that
The multiplying villanies of nature. Do swarm upon him--from the western isles of kerns and gallowglasses is supplied; and fortune, on his damned quarrel smiling,
Show\'d like a rebel\'s whore: but all\'s too weak: For brave Macbeth--well he deserves that name-- Disdaining fortune, with his brandish\'d steel,
which smoked with bloody execution like valour\'s minion carved out his passage till he faced the slave; Which ne\'er shook hands, nor bade farewell to him
till he unseam\'d him from the nave to the chaps and fix\'d his head upon our battlements.
<b>Duncan</b>: O valiant cousin! worthy gentleman! <br /> <br />
** Please press enter ** <br />';*/
}
public function p4($action)
{
$_SESSION['p'] = 'p1';
echo 'test 2';
}
}
?>
core2.php -
<?php
class Action
{
public function ContinueStory($p, $action)
{
$story = new Story;
if ($p == "p1")
{
$story->p2($action);
}
else if ($p == "p3")
{
$story->p3($action);
}
else if ($p == "p4")
{
$story->p4($action);
}
}
}
?>
Your problem is here :
<?php
echo 'DEBUG: P_'.$part.' <br />';
if ($_SESSION['p'] == 'p1')
$story->p1();
else
$action->continueStory($part, '');
if (isset($_POST['submit']))
{
$action->ContinueStory($part, $_POST['yourAction']);
}
?>
You're doing
$action->continueStory($part, '');
twice. First in your first 'if else', and secondly in your "if isset $_POST".
This should be the best way :
<?php
echo 'DEBUG: P_'.$part.' <br />';
if (isset($_POST['submit']))
{
$action->ContinueStory($part, $_POST['yourAction']);
} else {
if ($_SESSION['p'] == 'p1')
$story->p1();
else
$action->continueStory($part, '');
}
?>
N.B. : For security purpose, don't use $_SERVER['PHP_SELF'] in your form action, just #_ should be better I think!
I want to validate form using php and then make the input save in json file. I used span class to echo the error message from writer.php to html. But it's not echo the error text in html, it's refer to writer.php with blank page.
<head>
<title>Data Buku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="center">
<h1>Data Buku</h1>
<p><span class="error">* required field.</span></p>
<hr>
<form action="writer.php" method="post">
<span class="error"><?php echo $error;?></span>
<h2>Informasi Pengarang</h2>
Nama: <br><input type="text" name="nama" id="nama" />
<span class="error">* <?php echo $namaErr;?></span><br>
Nomor Telepon: <br><input type="text" name="telepon" id="telepon" />
<span class="error">* <?php echo $nomorErr;?></span><br>
e-Mail: <br><input type="email" name="email" id="email" />
<span class="error">* <?php echo $emailErr;?></span><br>
<h2>Tulisan</h2>
Judul: <br><input type="text" name="judul" id="judul" />
<span class="error">* <?php echo $judulErr;?></span><br>
Konten: <br><textarea name = "konten" rows="6" cols="50" id="konten"></textarea>
<span class="error">* <?php echo $kontenErr;?></span><br>
<input type="submit" id="submit" name = submit value="Create" />
<input type="reset" id="reset" value="Reset" />
</form>
</div>
</body>
This is my php file
<?php
// Append new form data in json string saved in json file
// path and name of the file
$filetxt = 'dataInJson.json';
// error message
$namaErr = "";
$nomorErr = "";
$emailErr = "";
$judulErr = "";
$kontenErr = "";
// check if all form data are submited, else output error message
if(isset($_POST['submit'])) {
// if form fields are empty, outputs message, else, gets their data
if(empty($_POST['nama'])) {
$namaErr = "Write your name";
}
if(empty($_POST['telepon'])){
$nomorErr = "Write the phone number";
}
if(empty($_POST['email'])){
$emailErr = "Write the email";
}
if(empty($_POST['judul'])){
$judulErr = "Write the title";
}
if(empty($_POST['konten'])) {
$kontenErr = "Write the content";
}
else {
// gets and adds form data into an array
$data = array(
'nama'=> $_POST['nama'],
'telepon'=> $_POST['telepon'],
'email'=> $_POST['email'],
'judul'=> $_POST['judul'],
'konten'=> $_POST['konten'],
);
// path and name of the file
$filetxt = 'dataInJson.json';
$arr_data = array(); // to store all form data
// check if the file exists
if(file_exists($filetxt)) {
// gets json-data from file
$jsondata = file_get_contents($filetxt);
// converts json string into array
$arr_data = json_decode($jsondata, true);
}
// appends the array with new form data
$arr_data[] = $data;
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
// saves the json string in "dataInJson.json"
// outputs error message if data cannot be saved
if(file_put_contents('dataInJson.json', $jsondata)){
echo '<script type="text/javascript">alert("Data has been submitted");</script>';
}
else{
echo 'Tidak dapat menyimpan data di "dataInJson.json"';
}
}
}
else echo 'Form fields not submited';
?>
You would need the page to submit to itself unless you did an AJAX solution so this would all have to be on one page:
<?php
error_reporting(E_ALL);
class ValidateInfo
{
public $errors;
public $message;
public $data;
public function Check($payload = array(),$type = "error",$mess = "unknown",$validate = array())
{
$trimmed = trim($payload[$type]);
if(!empty($validate)) {
// Strip out everything but numbers and letters and a couple of symbols.
if(in_array('digits',$validate) && in_array('letters',$validate)) {
$this->data[$type] = preg_replace('/[^0-9a-zA-Z\s\-\_]/','',$trimmed);
}
// Strip out all but numbers
elseif(in_array('digits',$validate)) {
$this->data[$type] = preg_replace('/[^0-9]/','',$trimmed);
}
// Strip out letters
elseif(in_array('letters',$validate)) {
$this->data[$type] = preg_replace('/[^a-zA-Z\s\-\_]/','',$trimmed);
}
// Re-assign data type to consolidate
$this->data[$type] = (!isset($this->data[$type]))? $trimmed:$this->data[$type];
// Check if data is an email
if(in_array('email',$validate)) {
$this->data[$type] = (filter_var($this->data[$type], FILTER_VALIDATE_EMAIL))? $this->data[$type]:'';
}
// Strip out html tags
if(in_array('strip',$validate)) {
$this->data[$type] = strip_tags($this->data[$type]);
}
}
if(!isset($this->data[$type]))
$this->data[$type] = $trimmed;
$this->errors[$type] = (empty($this->data[$type]))? 1:0;
$this->message[$type] = $mess;
}
}
// Creat instance of info processor
$info = new ValidateInfo();
// check if all form data are submited, else output error message
if(isset($_POST['submit'])) {
// Checks empty fields
$info->Check($_POST,'nama','Write your name',array('letters','digits'));
$info->Check($_POST,'telepon','Write the phone number',array('digits'));
$info->Check($_POST,'email','Write the email',array('email'));
$info->Check($_POST,'judul','Write the title',array('letters','digits'));
$info->Check($_POST,'konten','Write the content', array('letters','digits','strip'));
if(array_sum($info->errors) == 0) {
// path and name of the file
$filetxt = 'dataInJson.json';
// Assign stored data
$data = $info->data;
// path and name of the file
$filetxt = 'dataInJson.json';
// to store all form data
$arr_data = array();
// check if the file exists
if(file_exists($filetxt)) {
// gets json-data from file
$jsondata = file_get_contents($filetxt);
// converts json string into array
$arr_data = json_decode($jsondata, true);
// appends the array with new form data
$arr_data[] = $data;
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
// saves the json string in "dataInJson.json"
// outputs error message if data cannot be saved
if(file_put_contents('dataInJson.json', $jsondata)) {
$info->errors['success'] = true; ?>
<script type="text/javascript">
alert("Data has been submitted");
</script>
<?php }
else {
$info->message['general']['put_file'] = 'Tidak dapat menyimpan data di "dataInJson.json"';
}
}
else {
$info->message['general']['bad_file'] = 'No file exists';
}
}
}
else
$info->message['general']['submit'] = 'Form fields not submited'; ?>
<head>
<title>Data Buku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>
<style>
.error { color: red; clear: left; float: left; display: inline-block; width: 100%; font-size: 12px; }
input,
textarea { float: left; clear: left; display: inline-block; font-size: 20px; color: #333; padding: 10px; }
label { font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: #888; float: left; clear: left; display: inline-block; }
div.roadie { width: 500px; border-bottom: 1px solid #CCC; display: inline-block; float: left; clear: both; padding: 10px; }
</style>
<body>
<div class="center">
<h1>Data Buku</h1>
<?php if(isset($info->errors['success'])) { ?>
<h2>Thank you!</h2>
<?php } else { ?>
<p><span class="error">* required field.</span></p>
<?php } ?>
<hr>
<form action="" method="post">
<?php if(isset($info->message['general'])) {
foreach($info->message['general'] as $_error) { ?>
<span class="error">* <?php echo $_error; ?></span><br>
<?php
}
} ?>
<h2>Informasi Pengarang</h2>
<div class="roadie">
<label for="nama">Nama:</label>
<input type="text" name="nama" id="nama"<?php if(isset($info->data['nama'])) { ?> value="<?php echo strip_tags($info->data['nama']); ?>" /><?php } ?>
<?php if(isset($info->errors['nama']) && $info->errors['nama'] == 1) { ?><span class="error">* <?php echo $info->message['nama']; ?></span><?php } ?>
</div>
<div class="roadie">
<label for="telepon">Nomor Telepon:</label>
<input type="text" name="telepon" id="telepon"<?php if(isset($info->data['telepon'])) { ?> value="<?php echo strip_tags($info->data['telepon']); ?>"<?php } ?> />
<?php if(isset($info->errors['telepon']) && $info->errors['telepon'] == 1) { ?><span class="error">* <?php echo $info->message['telepon']; ?></span><?php } ?>
</div>
<div class="roadie">
<label for="email">e-Mail:</label>
<input type="email" name="email" id="email"<?php if(isset($info->data['email'])) { ?> value="<?php echo strip_tags($info->data['email']); ?>"<?php } ?> />
<?php if(isset($info->errors['email']) && $info->errors['email'] == 1) { ?><span class="error">* <?php echo $info->message['email']; ?></span><br><?php } ?>
</div>
<div class="roadie">
<h2>Tulisan</h2>
<label for="judul">Judul:</label>
<input type="text" name="judul" id="judul"<?php if(isset($info->data['judul'])) { ?> value="<?php echo strip_tags($info->data['judul']); ?>"<?php } ?> />
<?php if(isset($info->errors['judul']) && $info->errors['judul'] == 1) { ?><span class="error">* <?php echo $info->message['judul']; ?></span><?php } ?>
</div>
<div class="roadie">
<label for="konten">Konten:</label>
<textarea name = "konten" rows="6" cols="50" id="konten"><?php if(isset($info->data['konten'])) { echo strip_tags($info->data['konten']); } ?></textarea>
<?php if(isset($info->errors['konten']) && $info->errors['konten'] == 1) { ?><span class="error">* <?php echo $info->message['konten']; ?></span><br><?php } ?>
</div>
<input type="submit" id="submit" name = submit value="Create" />
<input type="reset" id="reset" value="Reset" />
</form>
</div>
</body>
Your if/else statements are wrong. Your else execute only if !empty($_POST['konten']).
I suggest you, pull errors in to one array, stored in session in redirect user (if scripts in different files) and show content of errors array. If you have trouble with logic, view this question here - PHP form validation submitting