PHP - Handling A Form
A 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? Similar TutorialsHello 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 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 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 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 ............................ } ?> This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=333815.0 This doesn't work. Based off what I have seen online, it is suppose to. Basically, this is what I tried, and the quote is what was returned. I have no idea how to get this to work. It should have been pretty standard based off of the PHP documentation. The Xpath idea I got from someone else. Either way if I try to use find element by id or tag name it still returns an empty array, no matter what. Any advice on what I am doing wrong is appreciated. It doesn't matter what URL I try, none of them seem to work. Code: [Select] <?php $school_data = file_get_contents('http://www.infotechnologist.biz'); $doc = new DOMDocument(); $doc->validateOnParse = true; $doc->loadHTML($school_data); $xpath = new DOMXPath($doc); $tags = $xpath->query('div'); echo '<pre>'; print_r($tags); echo '</pre>'; ?> Quote DOMNodeList Object ( ) 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 Hi ..am new to PHP and am using it to solve some mathematical problems which require extensive computation. Following is a code to solve a problem: Code: [Select] <?php $num =1; $n =0; $temp = 0; $count =0; $Final =0; While( $num < [color=orange]1000000)[/color] { $n = $num; while($n >1) { if(( $n % 2) == 0) { $n = $n/2; $temp++; } else { $n =3*$n +1; $temp++; } } If($temp > $count) { $count =$temp; $Final =$num; } $num++; $temp =0; } echo $Final; echo "<BR>"; echo $count; ?> I am running into "Maximum execution time of 30 seconds exceeded" error...its happening coz of the number 1 million...the code wrks fine for 100,1000,10000 and 100000...but breaks down @ 1000000.....is there any way to solve this situation...or PHP is not capable of handling huge numbers? please help...am stuck with this even though am so close to solving the prob. Thanks Abhijeet Hi, I'm a beginner in PHP OOP and I'm with some doubts about the correct way of handling errors in PHP. Look at this function for example: public function deleteFileFromDisk($fileNameToBeDeleted) { $handle = unlink($fileNameToBeDeleted); if (!$handle) { $result = "(this->deleteFileFromDisk) - Error, " . $fileNameToBeDeleted . " not deleted."; } else { $result = "(this->deleteFileFromDisk) - Success, " . $fileNameToBeDeleted . " deleted."; } return $result; } Is this the correct way of doing it, or I can do better than this? Let me add some details of what I'm achieving... I'm running class methods, and I need to control errors in the process. If any call to the object throw an error I need to catch, stop all the process and send an e-mail with the error. Here are the object interactions: $testar_classe = new geoIpImportCSV('geolitecity', 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/'); $testar_classe->downloadAndSaveFile('./', $testar_classe->obtainDownloadFileName()); $testar_classe->uncompressZipFile($testar_classe->obtainDownloadFileName(), '.'); $testar_classe->deleteLine(1, 'GeoLiteCity-Location.csv'); $testar_classe->deleteLine(1, 'GeoLiteCity-Blocks.csv'); $testar_classe->deleteDataFromTable('tabela1'); $testar_classe->deleteDataFromTable('tabela2'); $testar_classe->insertLinesToDb('GeoLiteCity-Location.csv', 'tabela1'); $testar_classe->insertLinesToDb('GeoLiteCity-Blocks.csv', 'tabela2'); $testar_classe->deleteFileFromDisk($testar_classe->obtainDownloadFileName()); $testar_classe->deleteFileFromDisk('GeoLiteCity-Blocks.csv'); $testar_classe->deleteFileFromDisk('GeoLiteCity-Location.csv'); Which is the best way of handle this? Create a new method to take care of the exceptions? There are any examples on how to do this? Best Regards. I am inserting last names into the database using mysql_real_escape_string(), and outputting the data into a textbox using addslashes(). When I try to display O'Brian "O\" is displayed in the text box. The name is saved corretly as O'Brian in the database. I am printing the string like this: Code: [Select] echo "<input type='text' value='" . addslashes($customer['lName']) . "' blah blah..."; anybody have any ideas? 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'm completely new to error handling in PHP and wanted to ask whether I'm doing it right and, if not, what the right way would look like class DBConnection { public function execute($sql) { $query = @pg_query($this->dbconn, $this->prepare($sql)); try { if (!$query) { throw new DBException(); } } catch (DBException $e) { echo "Query execution failed"; exit; } } } Whats the best way to handle database errors. I been using ob_start() stuff to run the code and if a database connection error occurs an variable $error turns to 1 and it displays the error code instead of the normal page that should be displayed when no errors occur. It works but I want to know if there is any better way to manage a db connection error while running a script. Also, how do you manage a problem when like 3 queries are ran to setup a new user account and the last one fails because the db connection drops or something, how would you go about handling a 2/3 query successful? I'm really stuck on how to manage errors if a db connection fails after the first connection is successful. 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 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 Hello there, I'm having a problem displaying money correctly with php. I have a field called "balance" with the type float(10,2), in this field I have a number store as "34.55" which I can go in and look at within phpmyadmin but when I echo this value on the front-end of the site it is displayed as "34.549999237061" Can someone please help? Regards. |