PHP Array Size Loop - php

We need to create a program that lets the user input the array size, their name, and age (depending on the array size the user entered). After that, we need to display all the elements of the array.
This is my code, but I'm having a problem adding a new element for another user and displaying it.
<html>
<head>
<title> PHP Array </title>
</head>
<body>
<form method="post" action="example.php">
<h3> Please enter the your information: </h3>
Array Size: <input type="text" name="arraysize"/> <br/><br>
Name: <input type="text" name="name" /><br/><br/>
Age: <input type="text" name="age"/> <br/><br/>
<input type="submit" name="submit" value="Submit"/>
<input type="reset" name="cancel" value="Cancel"/><br/><br/>
<?php
if(isset($_POST['submit'])){
if((!empty($_POST['name'])) && (!empty($_POST['age'])) && (!empty($_POST['arraysize']))){
$info = array($_POST['arraysize'], $_POST['name'], $_POST['g6ave']);
$arraylength = count($info);
for ($i=0; $i<=$arraylength ; $i++) {
$name = $_POST['name'];
for ($j=1; $j<=$i; $j++){
echo "User's Name" .$i. ": " .$name. [$j] ."<br>";
$age = $_POST['age'];
for($k=0; $k<=$i; $k++){
echo "User's Age: " .$age. [$k] ."<br/>";
}
}
}
}
}
?>
</body>
</html>

One approach (of other possible approaches) below should give you the main ideas. I also commented the aim of the each script part.
Approach below assumes that you'll use same URL for all your form pages. (1st, 2nd and the success page)
I hope this helps.
session_start(); //Start new or resume existing session
if (isset($_SESSION['form_success']) && $_SESSION['form_success'] === true)
{
require 'success_page.php';
unset($_SESSION['form_success']); // don't needed anymore
return; //not to continue to execute the code
}
// decide the page from user
if (isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
// display the first form page for the 1st time
require 'first_page_form.php';
return; //not to continue to execute the code
}
// if the first page was submitted.
if ($page === 'first') // or a specific POST flag from 1st page
{
//verify data from first page
$warnings = [];
if (first_page_data_valid() === true)
{
require 'second_page_form.php';
return; //not to continue to execute the code
}
// populate $warnings during first_page_data_valid()
//if first page data are invalid
print_r($warnings);
require 'first_page_form.php'; //display again
return; //not to continue to execute the code
}
// if the second page was submitted.
if ($page === 'second') // or a specific POST flag from 2nd page
{
//verify data from second page
$warnings = [];
if (second_page_data_valid() === true) // populate $warnings during second_page_data_valid()
{
// do things. ex: DB operations.
if (db_actions_success() === true)
{
$_SESSION['form_success'] = true; // defined and set to true.
// PHP permanent URL redirection. usage of 301 is important.
// it clears POST content. Prevents F5/refresh.
header("Location: https://www.url.com/form.php", true, 301);
exit; // good/recommended to use after redirect
}
else
{
echo 'System down or I have a bug. Try again later.';
return; //not to continue to execute the code
}
}
//if second page data is invalid
print_r($warnings);
require 'second_page_form.php'; //display again
return; //not to continue to execute the code
}

Related

PHP - Updating form data. (on same page)

I need to be able to update my form data once the submit button is pressed on the same page.
I have a csv file. And at the moment, I have worked out how to edit data inside it, and save it in the csv file (through a form).
-(I have attached the main code below, but even any suggestions would be helpful)
The form and php execution is on the same page, but once the user edits the values and presses submit, the data goes back to the original data. So it updates in the csv file, but not in the form.
This is the form:
for ($i=0; $i<200; $i++) {
if(empty($SearchResults[$i][0]) == false){ //If its full
?>
<form method="post" action="">
Full Name: <input name = "Name2" type="text" value="<?php echo $SearchResults[$i][0] ?>"/>
Weight (kg): <input name="Weight2" type="number" value="<?php echo $SearchResults[$i][1] ?>"/>
Weight of belongings (kg): <input name="WeightOfBelongings2" type="number"value="<?php echo $SearchResults[$i][2] ?>"/>
<input name="submit" type="submit" />
</form>
<?php
$i++;
}else if (empty($SearchResults[$i][0]) == true){ //If it is empty
$i =201;
}
}
This is what happens when the submit button is pressed:
if (isset($_POST['submit'])) {
$FullName = $_POST['Name2'];
$Weight = $_POST['Weight2'];
$WeightOfBelongings = $_POST['WeightOfBelongings2'];
//Creates a new felon from the class in felen.php and assigns it to this variable $Felon
$Felen = new felen;
//This refers to a function in the class Felen. From this information it calculates the costs, ammounts etc. And saves it to a variable that can be called.
$Felen -> CreateFelen($FullName, $Weight, $WeightOfBelongings);
//This is a for loop that checks when there is an avaliable line to put the data into.
if ($FullName != "") {
$i = 0;
for ($i=0; $i<200; $i++) {
if(empty($csv[$i][0]) == false){ //If its full
if($csv[$i][0] == $_POST['Name2']){
//its only printing it if it is in the first row?
$csv[$i][0] = $FullName;
$csv[$i][1] = $Weight;
$csv[$i][2] = $WeightOfBelongings;
$csv[$i][3] = $Felen->FelenTotalWeight;
$csv[$i][4] = $Felen->UnassembliumRequired;
$csv[$i][5] = $Felen->ReassembliumRequired;
$csv[$i][6] = $Felen->CostOfUnassemblium;
$csv[$i][7] = $Felen->CostOfReassemblium;
$csv[$i][8] = $Felen->TotalCostOfJourney;
$i = 201;
}
}
}
//Saves the previous data and new changes to the csv file
//This opens to file as a write file
$fp = fopen('data.csv', 'w');
//This takes the array that has had data ddded to it and adds it to the file
foreach ($csv as $fields) {
fputcsv($fp, $fields);
}
//This closes the file
fclose($fp);
}
}
Thank you very much!

PHP If / Else statement going directly to the Else without waiting for form input

Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.

Creating an error in an else

Basically I want to add one last piece of validation, if nothing is selected on the items page then an error appears or the user is returned to another page.
When submit is selected the form action sends it to the confirm page and the below is executed which displays the items selected if there is 1 or more entered if ($partno == $varname & $qty > 0) but I dont no what to put in the else part to return an error or take the user back to the previous page.
<?php
$visitor = $_POST['visitor'];
echo "<p>" . 'Hello ' . "<b>" . $visitor . "</b> " . 'please confirm your purchase(s) below.' . "</p>";
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
$total = 0;
foreach ($_POST as $varname => $varvalue) {
$qty = $varvalue;
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname & $qty > 0) {
echo "<tr><td><img src='$image' width='50' height='50' alt='image'</td>
<td>$partno<input type='hidden' name='$partno' value=$partno></td><td>$name</td><td>£$price</td>
<td> $qty</td><td><input type='hidden' name='visitor' value=$visitor></td>
<td><input type='hidden' name='qty' value=$qty></td></tr>";
$total = $total + $price * $qty;
} else {
}
}
}
?>
You'd have something like this:
$errors = array();
foreach(...) {
if ($partno == $varname & $qty > 0) {
... code for "ok" stuff
} else {
$errors[] = "$partno is incorrect";
}
}
if (count($errors) > 0) {
die("Errors: " . implode($errors));
}
... proceed to "success" code ...
Basically, for every test that fails, you record a message. Once the loop exits, if there's any error messages, you display them and abort processing. If there's no errors, you proceed onwards with the rest of the code.
Why not use a try catch block?
try {
if (isset($_POST)) {
if (!$email) {
throw new Exception('email is not valid', 100);
}
// everything is good process the request
}
throw new Exception('Error!', 200);
} catch (Exception $e) {
if ($e->getCode == 200) {
// redirect
} else {
// do something else
}
}
throw an Exception in your If statement, then put your data in try/catch block, so it will catch an exception if error occured
Consider the following approach: both the form and the php code to do something with the form data are on the same page. If the form was posted, you'll first check if the form was ok, after that you'll do something with the submitted data. If the form was not valid, display an error message.
The advantage is: no die() in the middle of your code, no strange redirects, everything in one script.
// simplified code in example.php
<?php
// in this variable we'll save success/error messages to print it
$msg = "";
// run this php code if the form was submitted
if(isset($_POST['submit'])) {
// is the form valid?
if (strlen($_POST['username']) == 0) {
$msg = "Please enter a username";
}
else {
// all validation tests are passed, give the user a nice feedback
// do something with the data, e.g. save it to the db
$msg = "Your data was saved. Have a great day";
}
}
?>
<div class="msg"><?php print $msg; ?></div>
<form method="post">
<input type="text" name="username">
<input type="submit" name="submit" value="Submit">
</form>

jquery ajax success function works only once

I'm trying to implement a form that utilizes jquery's post feature to dynamically update the database. What I'm realizing is that after the user clicks the "update" button, the success function is called back just fine with a "Update successful" message.
The issue I have for the stackoverflow world is why on subsequent clicks (w/o refreshing the page) I'm not getting this same success message. Also, ironically my database is being updated, so I know the AJAX call is going through.
I've posted my code below:
JS
var TEAM = {
update: function() {
var form_data = $('form').serialize();
$.ajax({
type: "POST",
url: "../manager/edit_team.php",
data: form_data,
error: function() {
$('#status').text('Update failed. Try again.').slideDown('slow');
},
success: function() {
$('#status').text('Update successful!');
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
},
cache: false
});
}
}
// jQuery Code for when page is loaded
$(document).ready(function()
{
$("#update").on("click", function() {
TEAM.update();
});
});
PHP (I welcome any other comments as well)
require '../includes/config.php';
include '../includes/header.html';
// autoloading of classes
function __autoload($class) {
require_once('../classes/' . $class . '.php');
}
// Site access level -> Manager
$lvl = 'M';
// Assign user object from session variable
if (isset($_SESSION['userObj']))
{
$manager = $_SESSION['userObj'];
}
else
{
session_unset();
session_destroy();
$url = BASE_URL . 'index.php';
ob_end_clean();
header("Location: $url");
exit();
}
// Establish database connection
require_once MYSQL2;
// Assign Database Resource to object
$manager->setDB($db);
// Authorized Login Check
if (!$manager->valid($lvl))
{
session_unset();
session_destroy();
$url = BASE_URL . 'index.php';
ob_end_clean();
header("Location: $url");
exit();
}
// Check for a valid game sch ID, through GET or POST:
if ( (isset($_GET['z'])) && (is_numeric($_GET['z'])) )
{
// Point A in Code Flow
// Assign variable from myteams-m.php using GET method
$id = $_GET['z'];
}
elseif ( (isset($_POST['z'])) && (is_numeric($_POST['z'])) )
{
// Point C in Code Flow
// Assign variable from edit_team.php FORM submission (hidden id field)
$id = $_POST['z'];
}
else
{
// No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include '../includes/footer.html';
exit();
}
$team = new ManagerTeam();
$team->setDB($db);
$team->setTeamID($id);
$team->pullTeamData();
$flag = 0;
echo $flag . "<br />";
// Confirmation that form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{ // Point D in Code Flow
// Assume invalid values:
$tname = FALSE;
// Validate team name
if ($_POST['tname'])
{
$tname = $_POST['tname'];
}
else
{
echo '<p class="error"> Please enter a team name.</p>';
}
// Validate about team information
if ($_POST['abouttm'])
{
$abtm = trim($_POST['abouttm']);
}
else
{
$abtm = '';
}
// Check if user entered information is valid before continuing to edit game
if ($tname)
{
if($team->editTeam($tname, $abtm) == True)
{
echo '<p>Team was successfully updated</p>';
$flag = 1;
}
else
{
echo '<p>No changes were made</p>';
$flag = 2;
}
}
else
{ // Errors in the user entered information
echo '<p class="error">Please try again.</p>';
}
} // End of submit conditional.
echo $flag . "<br />";
// Point B in Code Flow
// Always show the form...
// Get team name attribute
$team->pullTeamData();
$teamname = $team->getTeamAttribute('tmname');
$about = $team->getTeamAttribute('about');
if ($teamname != '') // Valid user ID, show the form.
{
// Headliner
echo '<h2>Edit Team</h2>';
// Create the form:
echo '
<div id="EditTeam"></div>
<div id="Team">
<fieldset id="TeamDetails">
<legend>Edit Team</legend>
<form method="post" id="information">
<p id="status"></p>
<input type="hidden" name="z" value="' . $id . '" />
<p>
<label for="tname">New Team Name:</label><br/>
<input type="text" name="tname" id="tname" size="10" maxlength="45" value="' . $teamname . '" />
</p>
<p>
<label for="abouttm">Team Information:</label><br/>
<textarea id="abouttm" name="abouttm" cols="30" rows="2">"' . $about . '"</textarea><br />
<small>Enter something cool about your team.</small>
</p>
<p>
<input type="hidden" name="id" id="id">
<input type="button" value="update" id="update" />
</p>
</form>
</fieldset>
</div>';
}
else
{ //Not a valid user ID, kill the script
echo '<p class="error">This page has been accessed in error.</p>';
include '../includes/footer.html';
exit();
}
// Close the connection:
$db->close();
unset($db);
include '../includes/footer.html';
?>
You'll notice I also have a $flag defined to help with the debugging, but ironically it outputs 0 no matter the number of clicks to the "update" button. So there's no indication that the database is being updated, yet when I check the tables it certainly is.
I appreciate any help or pointers. Thanks,
#status message is not showing because you've hidden it by slideUp(), to show it again you need to slideDown() them.
success: function() {
$('#status').text('Update successful!');
-ADD-> $('#status').slideDown('slow');
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
Do it same way as you have done in error handler:
success: function(){
$('#status').text('Update successful!').slideDown('slow');
...
It seems that you know it already and just forgot it...
Other method that may be useful is stop() to make sure that previous animation is stopped when new one is starting., especially important when using long timeouts/animations.
(useful = can prevent other problems with visibility and makes sure that messages does not start jumping in and out)
(long = somewhere around 0,5-1,5 sec or more, if during this time can happen something else then it is long...)
For example, this will clear fx queue, finish running animation immediately and slideUp():
$('#status').stop(true, true).slideUp('slow');
You also asked suggestions for other parts of code
If you are using same code at least twice or if it is general method that could be reused make it reusable:
function redirect_to( $page ) {
session_unset();
session_destroy();
$url = BASE_URL . $page;
ob_end_clean();
header("Location: $url");
exit();
}
if ($condition == true) {
redirect_to( 'index.php' );`
}

Why is that !isset does not seem to work?

I am new to the world of PHP and have put together a form that multiplies an entered value. However when I attempt to validate if a person has not entered any values to return an error message, it does display the message. My code below. Appreciate if you could also suggest improvements.
<?php
$counter = 0;
if(isset($_POST["submit"])) {
$start = $_POST["start"];
$end = $_POST["end"];
$multiply = $_POST["multiplication"];
// if($_POST["start"] == "" && $_POST["end"] == "" && $_POST["multiplication"] == "") {
// print "Please enter some values";
// }
if(!isset($_POST["start"], $_POST["end"], $_POST["multiplication"])) {
print "Please enter some values";
}
// for($start;$start<$end;$start++) {
// $counter = $counter +1;
// $multiplication = $counter * $multiply;
// print "$counter <br />";
// print "$counter multiplied by $multiply = $multiplication <br />";
// }
}
?>
<html>
<head>
<title>Sample Multiplication</title>
</head>
<body>
<form name="multiply" method="post" action="multiplication_sample.php">
<input type="text" name="start" value="<?php if(isset($_POST["start"])) { print $start; } ?>">
<input type="text" name="end" value="<?php if(isset($_POST["end"])) { print $end; } ?>">
<input type="text" name="multiplication" value="<?php if(isset($_POST["multiplication"])) { print $multiply; } ?>">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST["submit"])) {
for($start;$start<$end;$start++) {
$counter = $counter + 1;
$multiplication = $counter * $multiply;
print "$counter multiplied by $multiply = $multiplication <br />";
}
}
?>
</body>
</html>
I think that isset will make sure a variable is not NULL, however, "blank" is not the same as null. If you submit a form with blank values, the variable is still being set, it is just empty.
When the form is submitted, the content of the input fields is sent to the server.
If those input fields are empty, the server gets an empty string for each input -- but it gets something ; so, the $_POST["start"], $_POST["end"], $_POST["multiplication"] items are set -- even if they only contain empty strings.
You could check :
If the fields contain an empty string : if ($_POST["start"] === '')
Or if if contains only blank spaces : if (trim($_POST["start"]) === '')
Or if they are empty : if (empty($_POST["start"]))
If the fields aren't defined your code will print your message in the html before the <html> tag appears. Most browsers won't display it or display it in an unexpected place.
You should move the message display somewhere in the html where the user could see it.
And as other pointed out, except on the first call of the page the fields will have an empty value but still exists (and so isset will return TRUE)
I hope, I understand you right. It is
if(!isset($_POST["start"], $_POST["end"], $_POST["multiplication"])) {
print "Please enter some values";
}
that works not as expected? It seems, that you assume an empty string means, that nothing is set, what is not true.
$x = "";
isset($x); // true
Use empty() or just $_POST['start'] == '' instead.

Categories