PHP - Multi -entrance Form Handling
I am totally newbie, doing my first project, after reading a PHP book.
The page I am trying to build is like a quiz: displays a simple form, get answers and display "Good/bad answer". This is easy, but the form needs to continue based on the first answers, something like 5-6 more steps. Each step depends on the data from the previous steps. Can I still use the approach like the example below? What happens to the variables when the PHP script is re-visited? can I assume their values are still valid? // The example I thought I will use: <?php // if form not yet submitted, display form if (!isset($_POST['submit'])) { ?> <form ................................................. . </form> <?php // if form submitted // process form input } else { ..... $num = $_POST['num']; .......... } else { echo ' my message ............................ } ?> Similar TutorialsA form needs to get answers of math quiz, returning numbers, up to 2 digits after the point. In all form examples I noticed the usage of: Code: [Select] ...<input type="text" name="name" /... Cant it be a number? floating or integer? why "text" ? Also, can I limit the form to accept numerical input only or would I need to learn Ajax for that? Once I have the answer, I need to compare it to the correct answer. The method I have in mind is to multiply the answer and the correct one by 100 and compare the integer part. Is there a pre-made function that can do the same? Hello everyone, I've recently asked a question about forms and Requinix mentioned PRG method of processing forms. The PRG idea solves my refresh and back button document expired problems but i notice something new: when i refresh a page or use the browser back button - then return to the PRG process - repeat a refresh or back button action - i notice that i can traverse the cache history as many times as my prg approach redirects me. I feel like i am not implementing this PRG method correctly, or is this correct? Here is the form process if it helps solve the problem: i have a login form which contains a CSRF token. when i submit the form i specify an action as /prg/ which submits the data to index.php in the prg folder. After processing the data, prg index.php redirects to the root (because you are logged in). One problem is that i have a logo on the login page that allows you to return to the root (localhost index page). When the form is not submitted or it contaiuns incorrect login data or the logo is clicked to return to homepage, then the history seems to repeat itself. I've read that people recommend to use a header 303 See Other but the result is the same. Basiclly, if i am implementing a prg correctly, then the question becomes how can i instruct a browser to ignore the redirect as if the cache contains only the index page? i cannot find prg examples that involve a csrf token and other links on the protected page (prg/index.php protected because you need a form submission with a csrf token and it only processes data then redirects.) I don't see this happening in professional sites like Google or Microsoft etc. what am i doing wrong? Not sure why the PHP variables in the code below aren't interpreting the values that they should be receiving from the HTML form. HTML form Code: [Select] <form action="handle_form.php" method="post"> <fieldset><legend>Enter your information in the form below</legend> <p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40" /></p> <p><b>Email Address:</b> <input type="text" name="email" size="40" maxlength="60" /></p> <p><b>Gender:</b> <input type="radio" name="gender" value="M" /> Male <input type="radio" name="gender" value="F" /> Female</p> <p><b>Age:</b> <select name="age"> <option value="0-29">Under 30</option> <option value="30-60">Between 30 and 60</option> <option value="60+">Over 60</option> </select> </p> <p><b>Comments:</b> <textarea name="comments" rows="3" cols="40"></textarea></p> </fieldset> <div align="center"><input type="submit" name="submit" value="Sumbit My Information" /></div> </form> PHP handle_form <?php #Script 2.2 handle_form.php $name = $_REQUEST['name']; $email = $_REQUEST['email']; $comments = $_REQUEST['comments']; echo "<p>Thank you, <b>$name</b>, for the following comments:<br /> <tt>$comments</tt></p> <p> We will reply to you at <i>$email</i>.</p>"; ?> Hi Guys, Can someone please tell me why no echo statements work after my heredoc :? Here's the code: Code: [Select] <?php switch($_POST['options']){ case '1': $selected1 = 'selected'; break; case '2': $selected2 = 'selected'; break; case '3': $selected3 = 'selected'; break; case '4': $selected4 = 'selected'; break; default: $selected1 = $selected2 = $selected3 = $selected4 = ''; } echo <<<END <html> <head> <script type="text/javascript"> function show_alert() { alert("I am an alert box!"); } function formSubmit() { document.getElementById("frm1").submit(); } </script> </head> <body> <form id="frm1" method="post" action="search.php" /> <select onclick="formSubmit()" name="options" size="1"> <option $selected1 value="1">date</option> <option $selected2 value="2">year</option> <option $selected3 value="3">country</option> <option $selected4 value="4">language</option> </ select> </body> </html> </form> END; if(isset($_POST['options'])){ echo "item chosen"; } It works when I put the 'isset' if clause before the heredoc and even weirder, if i add a submit input type in the form as the last field it works as is? ex: Code: [Select] <?php switch($_POST['options']){ case '1': $selected1 = 'selected'; break; case '2': $selected2 = 'selected'; break; case '3': $selected3 = 'selected'; break; case '4': $selected4 = 'selected'; break; default: $selected1 = $selected2 = $selected3 = $selected4 = ''; } echo <<<END <html> <head> <script type="text/javascript"> function show_alert() { alert("I am an alert box!"); } function formSubmit() { document.getElementById("frm1").submit(); } </script> </head> <body> <form id="frm1" method="post" action="search.php" /> <select onclick="formSubmit()" name="options" size="1"> <option $selected1 value="1">date</option> <option $selected2 value="2">year</option> <option $selected3 value="3">country</option> <option $selected4 value="4">language</option> <input type="submit"> </ select> </body> </html> </form> END; if(isset($_POST['options'])){ echo "item chosen"; } Any help would be greatly appreciated! Cheers D This is a tough one to summarize - especially in the Subject?! I need to insert a Comment which consists of: * article_id * member_id * body * status * created_on * approved_on * updated_on Only the "body" field is gathered from my "Add a Comment" form, and everything else either comes from the $_SESSION or from NOW() I am wondering if it would be easier to do Error-Handling and what-not if I created an Input for at least the first 4 fields above and populated the "Value" of those fields that already have values (e.g. "member_id")?? Then when the user clicks "Add a Comment", I can check all of the values in $_POST and handle everything in a uniform way, if you follow my new thinking?! Debbie Hi guys, What techniques do you use to process, validate, and then show errors on your forms. Do you set an "action" to the same form and then handle errors somewhere? Do you use a separate script to process validation? What standards do you apply for the position of the error messages? Do you alter the "look" of any fields in errors (make them red for example)? Do you have a good standard strategy that can be applied for all forms in a re-usable fashion? Perhaps using functions? I am looking for a robust, user friendly (and coder friendly come to that) solution to this frequently encountered situation. Many thanks for any help. S Hello All, I am building a web based data entry project for my University Recycling Department 1) In the first level the user will enter the number of "rows" that he has to enter it can be any number form 4- 10 . Each row will contain "Vendor Name","Date","Net Recycled Weight" 2) Depending on the number of rows entered by the user I am generating a table structure that has 2.1) A <select> containing vendor names(I am querying for this and then storing the result in an Associative Array and then parsing it for select in every way) 2.2) A text box for the date 2.3) A text box for the Net Recycled Weight ------------------------------------------------ Here is the logic I have implemented so far <html> <head></head> <body> <form name = "form1" method = "post"> <select>HERE THE USER CAN SELECT THE NUMBER OF ROWS HE WANTS TO ENTER</select> <input type = "submit" value = "submit1" name = "submit1"> </form> <body> </html> <?php if(submit1 has been clicked ) { //HERE I AM GENERATING A DYNAMIC FORM BASED ON THE NUMBER OF ROWS COUNT <form name = "form2" method = "post"> echo <table> echo <tr> echo<td>VENDOR</td> echo<td>DATE</td> echo<td>NET RECYCLED WEIGHT</td> echo </tr> for(IT ITERATES TILL I GENERATE THE NUMBER OF ROWS THAT HAS TO BE ENTERED) { I AM GENERATING ROWS HERE } echo <input type = "submit" name = "submit2" value = "submit2"> echo</table> </form> HOW CAN I ACCESS THE POST METHOD OF FORM 2 } ?> MY PROBLEM --------------- I WANT TO KNOW THE FOLLOWING 1) It this the correct way to do it 2) how can I access the data entered in each dynamic row as I have to validate it and then enter the data in MySql 3) I am not sure how I will access the submit button event of the dynamically generated form I hope I can get some help Thanks, Marisha I am learning how to use PHP to handle input in a Contact Form on my website. Using PHP I can send the form data to my email client. However I cannot achieve the outcome of sending a copy to the email address of the submitter. I have searched the Internet particularly Stack Overflow and have found code that I am told will achieve this outcome Here is the code: <?php if(isset($_POST['submit'])){ $to = "email@example.com"; // this is your Email address $from = $_POST['email']; // this is the sender's Email address $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $subject = "Form submission"; $subject2 = "Copy of your form submission"; $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message']; $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message']; $headers = "From:" . $from; $headers2 = "From:" . $to; mail($to,$subject,$message,$headers); mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender // echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly."; OR // You can also use header('Location: thank_you.php'); to redirect to another page. } ?> Adjusting it for my own circumstances and settings it will still send the information in the form to me but will not send the information to the submitter's email address. What is particularly confusing is, if I modify the code by taking out this line of code mail($to,$subject,$message,$headers); Which includes my email address ($to), it still works and the information including ($subject) is still sent to my email address. I would appreciate any assistance that anyone would offer This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=333815.0 Which one is better for standards practices in PHP. 1. Using the same form for everything. (Add and edit). Meaning setting up one form to handle adding new records, as well as editing existing records. Or 2. Using two different forms for both actions. Use one form/area to handle Adding, and one form/area to handle editing. Which one of these are better from a standards/practice point of a view. Which one better fits into the MVC platform (a framework like Codeignitor, or Cake). Should their be separate controller functions/views for add and edit or should they all be in the same controller function/form. Thanks for the feedback. hi , i want to make 5 forms with 1 submit button , how i do that? thanks , Mor. Can some one tell me how to convert this code to deal with multiple uploads into different folders. thanks in advance. Quote Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> <label>First Name</label><input type="text" name="fname" /><br /> <label>Last Name</label><input type="text" name="lname" /><br /> One <label>Upload Image</label> <input type="file" name="image" /><br> Two <label>Spec</label> <input type="file" name="spec" /><br /> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> <input type="submit" id="submit" value="Upload" /> </form> Quote Code: [Select] <?php function is_valid_type($file) { $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } $TARGET_PATH = "images/"; $fname = $_POST['fname']; $lname = $_POST['lname']; $image = $_FILES['image']; $fname = mysql_real_escape_string($fname); $lname = mysql_real_escape_string($lname); $image['name'] = mysql_real_escape_string($image['name']); $TARGET_PATH .= $image['name']; if ( $fname == "" || $lname == "" || $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: index.php"); exit; } if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: index.php"); exit; } if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: index.php"); exit; } if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { $sql = "insert into people (fname, lname, filename,spec) values ('$fname', '$lname', '" . $image['name'] ."')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: images.php"); exit; } else { $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: index.php"); exit; } ?> Hey guys, Recently I bumped into a little coding problem. I'm trying to submit information to a multi-part form (including an image upload). The receiving server couldn't read my input, figured I had a nill object somewhere (RoR). First I thought the problem was in my curl setopts, but I think they are fine. It looks like the problem is with the data I'm submitting. I read a bit about multi part posting, and every article I read advised to make a postfield array, which curl would interpret and send out correctly. I did and this was my resulting array: $postfield = array ("social[comments]" => "Test", "avatar_file" => "", "friend_avatar_file" => "", "forum_avatar_file" => "", "social[signature]" => "", "forum_signature_file" => "", "save_profile.x" => "25", "save_profile.y" => "9"); That failed. So I tried making it into a URLENCODED string: $postfield = "social%5Bcomments%5D=".stripslashes($_POST['textarea'])."&avatar_file=&friend_avatar_file=&forum_avatar_file=".$file."&social%5Bsignature%5D=&forum_signature_file=&save_profile.x=25&save_profile.y=9"; This finally worked. I was able to submit the info I wanted. I'd like to send a file with it this time though. I'd need to put this into a postfield array to work though. if(!$file = upload( )) { $file = ''; } else { $file = '@'.$file; } function upload( ) { if(isset($_FILES['file']) && !empty($_FILES['file']['name'])) { $uploaddir = "temp"; if(is_uploaded_file($_FILES['file']['tmp_name'])) { move_uploaded_file($_FILES['file']['tmp_name'],$uploaddir.'/'.$_FILES['file']['name']); $searchfile = $uploaddir.'/'.$_FILES['file']['name']; return $searchfile; } } return false; } So, I got the uploading covered. I need to put generate the postfield array though. I have the feeling the problem is with the brackets [ ] I'm using. I tried urlencoding the keys in the array, but that didn't work either. Does anybody have an idea on how to handle brackets in post (multi-part) data? Thanks in advance! Hi, I'm having problems retrieving the values from a form posting without getting a warning My form records playername, hours played and minutes played Code: [Select] <li id="input1" style="margin-bottom:4px;" class="clonedInput"> Name: <select name="player[1][userid]" id="player[1][userid]" class="playerInput" style="width: 7em;" > <option value=""></option> <?php while($row = mysql_fetch_array($sql)) { echo '<option value="'.stripslashes($row['userid']).'">'.stripslashes($row['name']).'</option>'; } mysql_data_seek($sql,0); ?> </select> <select name="player[1][hours]" id="player[1][hours]"> <option value="">Hours</option> <option value=""></option> <?php for($x = 0; $x <= 23; $x++ ) { echo '<option value="'.$x.'">'.$x.'</option>'; } ?> </select> <select name="player[1][minutes]" id="player[1][minutes]"> <option value="">Minutes</option> <option value=""></option> <?php for($y = 15; $y <= 59; $y+=15) { echo '<option value="'.$y.'">'.$y.'</option>'; } ?> </select> </li> I use some javascript to create new players as necessary so every player has a userid, hours, minutes played... After posting the query string looks like this /cLeagueHandler.php?player[1][userid]=1&player[1][hours]=3&player[1][minutes]=15&player[2][userid]=3&player[2][hours]=6&player[2][minutes]=45&submit=Save+Points player1 userid = 1 hours = 3 minutes = 15 player2....... The code i'm using to access the values is Code: [Select] print_r ($_GET); // test display form values foreach ($_GET as $key => $value) { echo '<br/>'.$key.'<br/> '; foreach ($value as $iKey => $iValue) { // Line 72 foreach ($iValue as $xKey => $xValue) { echo " The $xKey for Player $iValue is $xValue <br/>"; } } } The above code displays Array ( [player] => Array ( [1] => Array ( [userid] => 1 [hours] => 3 [minutes] => 15 ) [2] => Array ( [userid] => 3 [hours] => 6 [minutes] => 45 ) ) [submit] => Save Points ) player The userid for Player Array is 1 The hours for Player Array is 3 The minutes for Player Array is 15 The userid for Player Array is 3 The hours for Player Array is 6 The minutes for Player Array is 45 submit Warning: Invalid argument supplied for foreach() in .................cLeagueHandler.php on line 72 Line 72 is foreach ($value as $iKey => $iValue) { If anyone could help me with this it would be great appreciated.......I want to be able to build and sql string to Insert a players id, hours, minutes into a database......(obviously not incl the submit value!) Maybe this is not even the best way of approaching this.....I'm quiet new to PHP so apologies if this is long winded...I'm trying to give as much info as possible.... thanks in advance tmfl hi all i have a problem here, Iv got a form that uploads images to a folder and updates the db with the name of that image, that work ok but if one of the upload field are left blank then the script updates the db with empty values how can i get it to only update the db with only submitted form field data???? here is the form Code: [Select] <?php if (isset($_GET['id'])) { $id = $_GET['id']; } ?> <form action="ud_image.php?id=<? echo "$id"?>" method="post" enctype="multipart/form-data" name="form1" id="form1"> <table class="udp"> <tr> <th>Thumbnail:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 1:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 2:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 3:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <th>Image 4:</th> <td><input type="hidden" name="MAX_FILE_SIZE" value="1029120" /> <input name="ufile[]" type="file" id="ufile[]" size="50" /><input type="submit" name="Submit" value="Upload" /></td> </tr> </table> </form> and here is the processing page <?php include("protect/password_protect.php"); error_reporting(E_ALL); include ("../includes/db_config.php"); $con = mysql_connect($db_hostname,$db_username,$db_password); @mysql_select_db($db_database) or die( "Unable to select database"); $path1= "../thumbnails/".$_FILES['ufile']['name'][0]; $path2= "../images/".$_FILES['ufile']['name'][1]; $path3= "../images/".$_FILES['ufile']['name'][2]; $path4= "../images/".$_FILES['ufile']['name'][3]; $path5= "../images/".$_FILES['ufile']['name'][4]; //copy file to where you want to store file copy($_FILES['ufile']['tmp_name'][0], $path1); copy($_FILES['ufile']['tmp_name'][1], $path2); copy($_FILES['ufile']['tmp_name'][2], $path3); copy($_FILES['ufile']['tmp_name'][3], $path4); copy($_FILES['ufile']['tmp_name'][4], $path5); ?> <html> <head> <title>Update Project Images</title> <link rel="stylesheet" type="text/css" href="../../project/backend/style.css" /> </head> <body> <table class="udip"> <tr> <th><? echo "<img src=\"$path1\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path2\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path3\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path4\" width=\"150\" height=\"150\">";?></th> <th><? echo "<img src=\"$path5\" width=\"150\" height=\"150\">";?></th> </tr> <tr> <td><? echo "File Name :".$_FILES['ufile']['name'][0]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][1]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][2]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][3]."<BR/>";?></td> <td><? echo "File Name :".$_FILES['ufile']['name'][4]."<BR/>";?></td> </tr> <tr> <td><?echo "File Size :".$_FILES['ufile']['size'][0]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][1]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][2]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][3]."<BR/>";?></td> <td><?echo "File Size :".$_FILES['ufile']['size'][4]."<BR/>";?></td> </tr> <tr> <td><? echo "File Type :".$_FILES['ufile']['type'][0]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][1]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][2]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][3]."<BR/>";?></td> <td><? echo "File Type :".$_FILES['ufile']['type'][4]."<BR/>";?></td> </tr> </table> </body> </html> <? $filesize1=$_FILES['ufile']['size'][0]; $filesize2=$_FILES['ufile']['size'][1]; $filesize3=$_FILES['ufile']['size'][2]; $filesize4=$_FILES['ufile']['size'][3]; $filesize5=$_FILES['ufile']['size'][4]; if($filesize1 && $filesize2 && $filesize3 && $filesize4 && $filesize5 != 0) { echo "We have recieved your files<p>"; } else { echo "Error in you images check and try again Database has been updated to blank images so no images will be shown on details page."; } $query = "UPDATE $db_table SET thumbnail = '".$_FILES['ufile']['name'][0]."', image1 = '".$_FILES['ufile']['name'][1]."', image2 = '".$_FILES['ufile']['name'][2]."', image3 = '".$_FILES['ufile']['name'][3]."', image4 = '".$_FILES['ufile']['name'][4]."' WHERE id = '".$_GET['id']."'"; if (!mysql_query($query,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?> I have a prepared statement that returns an Article from my database. It then binds the results-set to variables. Most of the fields in the query are "required", so I *assume* that I am guaranteed to always get values back for those fields... Is that presumptuous? Here is a snippet of my code... // Execute query. mysqli_stmt_execute($stmt); // Store results. mysqli_stmt_store_result($stmt); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt)==1){ // Article was Found. $articleExists = TRUE; // Bind result-set to variables. mysqli_stmt_bind_result($stmt, $articleID, $title, $description, $keywords, $heading, $subHeading, $publishedOn, $author, $body, $referenceListing, $endnoteListing); // Fetch record. mysqli_stmt_fetch($stmt); // Close prepared statement. mysqli_stmt_close($stmt); // ???? Is it sufficient to have code like this... Code: [Select] <title><?php echo $title; ?></title> ...or do I need more error-handling?? Hope that makes sense?! Thanks, Debbie Hey Guys,
Been coding PHP for a while but I always wonder about the right way of doing things. I am building an online community which I want to display to members and non-members. With this each screen will have options that are available for members only. I have set up session variables once a user logged in but its getting really old having to nest if statements on ISSET then again to check the values in the variables if it is set. See example below.
Question 1. Is it ok to session_start(); for all site visitors?
Question 2. If Q.1 is ok then is it ok to set all the session variables upfront with blank values as placeholders. This would eliminate the need for ISSET.
if (ISSET($_SESSION['On'])) { if (in_array($GroupID, $_SESSION['Groups'])) { $IsMember = 1; } else {$IsMember = 0;} } else {$IsMember = 0;}Just wanted to get your thoughts on this. Thank you, Jeremy I have set an SQL field as unique so that duplicates can't be entered, however rather then having the page error out and show the Error: Duplicate entry 'entry' for key 'field' I would like to be able to have a little div appear and say something like "this entry already exists" I already have it set to show that the item has been added but I have no idea were to start to make this work. Any ideas? Thanks, Jim Hi, I have an HTML form created using Dreamweaver and now I need a script to handle the form processing. Basically what I need is for the form data received from the webpage to be organized in an email and then sent to me. I would also like to display a thank you message in the browser so the user knows it was received. I was planning to do this using CGI but a colleague suggested that CGI is old school and nowadays a developer would use PHP for this task. Is PHP the right solution for this project? The examples I have found so far always include the HTML for the form and the script needed to handle it in one file. In my case, I have an HTML form already in place and need it to work with a script to perform the email function. I know I need to set "Action=" on my webpage to point to the PHP script but what would the code look like if no HTML is needed? I hope this makes sense... Thanks for your help! Rob |