PHP - Add Form Errors Beside Label/input On Page?
Hello.
I have a basic form and I want to check for errors by making sure the user inputs everything, if not an error explaining to the user what needs to be fixed. (very common on all forms) When I use echo in my script, it displays at the top of my browser. How do I put the error codes right beside my form elements? I currently don't have all the error checking included but I want to get a few sorted out before anything else. Form Page: http://www.fusionfashionhair.com/registration.php My PHP Code all above DOCTYPE in the php file. Code: [Select] <?php $submit = $_POST['submit']; // Form Data // Check all form inputs using check_input function $name = strip_tags($_POST['name']); $address = strip_tags($_POST['address']); $email = strip_tags($_POST['email']); $repeatemail = strip_tags($_POST['repeatemail']); $phone = strip_tags($_POST['phone'], "Enter your Phone Number"); $salonname = strip_tags($_POST['salonname']); $salonaddress = strip_tags($_POST['salonaddress']); $salonprov = strip_tags($_POST['salonprov']); $salonpostal = strip_tags($_POST['salonpostal']); $salonconfirm = strip_tags($_POST['salonconfirm']); $enewsletter = strip_tags($_POST['enewsletter']); $saloncountry = strip_tags($_POST['saloncountry']); $password = strip_tags($_POST['password']); $repeatpassword = strip_tags($_POST['repeatpassword']); $date = date("Y-m-d"); // Set e-mail recipient $myemail = "info@fusionfashionhair.com"; if ($submit) { //check for existance if ($name&&$password&&$repeatpassword&&$email) { if ($password==$repeatpassword) { if ($email==$repeatemail) { //check password length if (strlen($password)>32||strlen($password)<6) { echo '<p class="formecho">Password must be between 6 and 32 characters</p>'; } else { // Thank you Page $insertGoTo = "thankyou.php"; header(sprintf("Location: %s", $insertGoTo)); // encrypt password $temppass = $password; $password = md5($password); $repeatpassword = md5($repeatpassword); // dBase file include "dbConfig.php"; //open database //generate random number for activation process $random = md5(rand(23456789,987654321)); // register the user! // Set default username $username = $email; // INSERT INTO user... replace user with table name // make sure you have the same number and order of values as the database has $queryreg = mysql_query(" INSERT INTO user VALUES ('','$name','$username','$password','$date','$email','$phone','$address','$salonname','$salonaddress','$salonprov','$salonpostal','$saloncountry','$salonconfirm','$enewsletter','$random','0')"); //Insert ID based on last ID in database $lastid = mysql_insert_id(); //send activation email $to = $email; $subject = "Activate Salon Member Acctount at Fusion Fashion Hair"; $headers = "From: webmaster@fusionfashionhair.com"; $server = "mail.fusionfashionhair.com"; //change php.ini and set SMTP to $server ini_set("SMTP",$server); $body = " $name from $salonname is wanting a membership, \n\n Please click on the link provided below to activate the account with Fusion Fashion Hair http://www.fusionfashionhair.com/activate.php?id=$lastid&code=$random \n\n Username = $username \n Password = $temppass \n Thank you, Customer Service "; //function to send email mail($to, $subject, $body, $headers); } } else echo '<p class="formecho">Your passwords do not match!</p>'; } else echo '<p class="formecho">Your Emails do not match!</p>'; }//End check Existance else echo '<p class="formecho">Please fill in <b>ALL</b> fields!</p>'; }// End if Sumbit ?> Similar TutorialsI built a basic form with certain fields required. When a required field isn't filled, the errors are echoed but not in the best area. I'd like for each error message to be displayed underneath their respected input fields. What do I need to look into? <?php if(!empty($_POST['submit'])) { // set variables $name = mysql_real_escape_string($_POST['name']); $email = mysql_real_escape_string($_POST['email']); $email2 = mysql_real_escape_string($_POST['email2']); $age = mysql_real_escape_string($_POST['age']); $city = mysql_real_escape_string($_POST['city']); $state = mysql_real_escape_string($_POST['state']); // 1A. REQUIRED FIELDS VERIFICATION if(!empty($name) && !empty($email) && !empty($email2) && !empty($city) && !empty($state)) { // 1B. END REQUIRED FIELDS VERIFICATION } else { echo '<img src="images/icon_error.png" alt="" title="" /> Please fill out the required fields.<br />'; if (empty($name)) { echo 'Whats your name?!<br />'; } if (empty($email)) { echo 'No email given.<br />'; } if (empty($email2)) { echo 'Please verify your email<br />'; } if (empty($city)) { echo 'What city are you from?<br />'; } if (empty($state)) { echo 'What State!<br />'; } echo '<br /><br />'; } // 1B. END REQUIRED FIELDS ERROR CODES } ?> <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <div class="formSec"><label for="name" class="required">Full Name:</label> <input type="text" name="name" id="name" value="" /></div> <div class="formSec"><label for="email" class="required">Email:</label> <input type="text" name="email" id="email" value="" /></div> <div class="formSec"><label for="email2" class="required">Confirm Email:</label> <input type="text" name="email2" id="email2" value="" /></div> <div class="formSec"><label for="age" class="required">Age:</label> <input type="text" name="age" id="age" value="" /></div> <div class="formSec"><label for="city" class="required">City:</label> <input type="text" name="city" id="city" value="" /></div> <input class="submit" type="submit" name="submit" value="Submit" /> </form> Is it possible to have a link at the top of a page that has been displayed from a database? Just that some results show thousands of rows. Thanks.
Hello everyone. I need help with the following PHP APP. I am running on (Version PHP 7.2.10) I am trying to have a page table form on table.php pass the input variable of “5-Numbers” to another page called table_results.php I want that variable string of “5-Numbers” to be compared against 4 arrays and output any duplicates found within each of those 4 lists. If nothing is found, I still want some visual output that reads “None found”.
Lets pretend I have the following example .. On table.php, I typed inside my table form the 5-Numbers .. INPUT: 2,15,37,13,28 On table_results.php, the 4 arrays to be compared against my input numbers “ 2,15,37,13,28” are ..
$array_A = array(2,6,8,11,14,18,24); $array_B = array(1,2,9,10,13,14,25,28,); $array_C = array(1,3,7,9,13,15,20,21,24); $array_D = array(4,5,12,22,23,27,28,29);
So my output should read as follows below .. OUTPUT:
TABLE COLUMN 1 COLUMN 2 ROW 1 Matches Found Results .. ROW 2 GROUP A: 2 ROW 3 GROUP B: 2,13,28 ROW 4 GROUP ? 13,15 ROW 5 GROUP ? 28 ROW 6 5#s Input: 2,15,37,13,28
Please let me know if anyone has any suggestions on how to go about it. Thanks. Edited January 1, 2019 by Jayfromsandiego Wanted to include image example Hi people, I really hope you guys can help me out today. I'm just a newbe at php and i'm having real trouble. Bassically all I want to do is have a user type in a company name in a html form. If what the user types in the form matches the company name in my php script i want the user to be sent to another page on my site. If what the user types in the form doesnt match the company name in my php script i want the user to be sent to a differnt page like an error page for example. this is my html form: Code: [Select] <form id="form1" name="form1" method="post" action="form_test.php"> <p>company name: <input type="text" name="company_name" id="company_name" /> </p> <p> <input type="submit" name="button" id="button" value="Submit" /> </p> </form> And this is the php code I'm trying to process the information on: Code: [Select] <?php $comp_name = abc; if(isset ($_POST["company_name"])){ if($_POST["company_name"] == $comp_name){ header("Location: http://www.hotmail.com"); exit(); } else{ header("Location: http://www.yahoo.com"); exit(); } } ?> The thing is i'm getting this error when i test it: Warning: Cannot modify header information - headers already sent by (output started at D:\Sites\killerphp.com\form_test.php:10) in D:\Sites\killerphp.com\form_test.php on line 17 Please can some one help me out, i'm sure this is just basic stuff but i just cant get it to work Cheers. I have created (modified a tutorial) a PHP Validation Form with validation. I am getting a blank page and cannot view it. <?php error_reporting(E_ALL); ini_set('display_errors', 1); ?> <?php function VerifyForm(&$values, &$errors) { // Do all necessary form verification // Validate Model Number if (strlen($values['model']) < 4) $errors['model'] = 'Model Number too short'; elseif (strlen($values['model']) > 50) $errors['model'] = 'Model Number too long'; // Validate Price if (is_numeric($values['price']) == 0) $errors['price'] = 'No Price has been entered'; // Validate Product if(($values['product'])=='please_select') $errors['product'] = 'No Product has been selected'; // Validate Image if ((($_FILES["photo"]["type"] != "image/gif") || ($_FILES["photo"]["type"] != "image/jpeg") || ($_FILES["photo"]["type"] != "image/pjpeg")) && ($_FILES["photo"]["size"] > 2000000)) $errors['photo'] = 'Image format must be either JPG/JPEG/GIF or PNG'; // Validate Description if (strlen($values['description']) < 10) $errors['description'] = 'Description is too short'; return (count($errors) == 0); } function DisplayForm($values, $errors) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>swiftelectrical.net - Test Area</title> <link rel="stylesheet" href="test.css" type="text/css" media="screen" /> <style> TD.error { color: red; font-weight: bold; } </style> </head> <body> <div id="container"> <h1>Add a Product</h1> <?php if (count($errors) > 0) echo "<p>There were some errors in your submitted form, please correct them and try again.</p>"; ?> <form method="post" id="customForm" action="<?php = $_SERVER['PHP_SELF'] ?>" enctype="multipart/form-data"> <table> <tr> <td>Model Number:</td> <td><input id="model" type="text" size="30" name="model" value="<?php = htmlentities($values['model']) ?>"/></td> <td class="error"><?php = $errors['model'] ?></td> </tr> <tr> <td>Choose a Product:</td> <td> <select class="product" name="product"> <option value="please_select">Please select an option below</option> <option value="1">19" LCD TV</option> <option value="2">22" LCD TV</option> <option value="3">26" LCD TV</option> <option value="4">32" LCD TV</option> <option value="5">37" LCD TV</option> <option value="6">42" LCD TV</option> <option value="7">37" Plasma TV</option> <option value="8">42" Plasma TV</option> <option value="9">46" Plasma TV</option> <option value="10">50" Plasma TV</option> <option value="11">54" Plasma TV</option> <option value="12">58" Plasma TV</option> <option value="13">Wall Bracket</option> <option value="14">Home Cinema System</option> <option value="15">Bluray Home Cinema System</option> <option value="16">DVD Recorder</option> <option value="17">DVD Player</option> <option value="18">DVD Portable</option> <option value="">Bluray Recorder</option> <option value="">Bluray Player</option> <option value="">Bluray Portable</option> <option value="">Projector</option> <option value="">37" LCD TV</option> <option value="">42" LCD TV</option> <option value="">Personal Video Recorder (PVR)</option> <option value="">3D Technology</option> <option value="">Upright Cleaner</option> <option value="">Cylinder Cleaner</option> <option value="">DECT Phone</option> <option value="">DECT Answer Phone</option> <option value="">Washing Machines</option> <option value="">Tumble Dryers</option> <option value="">Dishwashers</option> <option value="">Fridge-Freezers</option> <option value="">Freezers</option> <option value="">Refridgerators</option> <option value="">Microwave (Solo)</option> <option value="">Microwave (Grill)</option> <option value="">Microwave Combination</option> <option value="">Kettles</option> <option value="">Toasters</option> <option value="">Irons</option> <option value="">Breadmakers</option> <option value="">Microsystems</option> <option value="">Minisystems</option> <option value="">CD, Radio and Cassette Players</option> <option value="">Pure Radios</option> <option value="">Dimplex Fires</option> <option value="">Convector Heaters</option> <option value="">Fan Heaters</option> <option value="">Mens Shavers/Grooming</option> <option value="">Ladies Shavers/Beauty</option> <option value="">Straighteners</option> <option value="">Epilators</option> <option value="">Stylish Cameras</option> <option value="">Super Zoom Cameras</option> <option value="">SD Camcorders</option> <option value="">HD Camcorders</option> <option value="">HDD Camcorders</option> <option value="">Bluray Discs</option> <option value="">DVD Discs</option> <option value="">Leads</option> <option value="">Mini DV Tapes</option> <option value="">SD/SDHC/SDXC Cards</option> </select> </td> <td class="error"><?php = $errors['product'] ?></td> </tr> <tr> <td>Price:</td> <td><input id="price" type="text" size="30" name="price" value="<?php = htmlentities($values['price']) ?>"/></td> <td class="error"><?php = $errors['price'] ?></td> </tr> <tr> <td>Please upload an Image:</td> <td><input id="photo" type="file" size="30" name="photo" value="<?php = htmlentities($values['photo']) ?>"/></td> <td class="error"><?php = $errors['photo'] ?></td> </tr> <tr> <td valign="top">Description:</td> <td> <textarea id="description" name="description" cols="30" rows="6"><?= htmlentities($values['description']) ?></textarea> </td> <td class="error"><?= $errors['description'] ?></td> </tr> <div> <input id="submmit" name="submit" type="submit" value="Send" /> </div> </table> </form> </div> </body> </html> <?php } function ProcessForm($values) { //INSERT VARIABLES FROM INSERT_ADD.PHP // Replace with actual page or redirect :P header ("Location: http://www.starjokes.com"); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { $formValues = $_POST; $formErrors = array(); if (!VerifyForm($formValues, $formErrors)) DisplayForm($formValues, $formErrors); else ProcessForm($formValues); } else DisplayForm(null, null); ?> Hey guys! Merry Christmas!!!! Here's my problem. I have a script where I use the code include("pagerefresh.php"); where pagerefresh.php is <?php $page = $_SERVER['PHP_SELF']; $sec = "0"; header("Refresh: $sec; url=$page"); ?> I use the include function several times on the page and everything's cool with it. But once I put this: <html> <head> <title>Title</title> <script type="text/javascript"> <?php some mysql function include("timecounter.js"); ?> </script> </head> in the page, the following error pops out whenever I use some of the form functions in the page. I read the php.net manuals and discovered that the include part should come before Code: [Select] Warning: Cannot modify header information - headers already sent by (output started at D:\Hosting\rrr\html\rrr\rrr\rrr.php:191) in D:\Hosting\rrr\html\rrr\rrr\pagerefresh.php on line 4 Oh, and I also put the javascript code directly into the page, without the include function, the same results pop out. :/ . Though I suspect that it is immaterial here, the javascript code is: Code: [Select] var month = '<?php echo "$cmonth"; ?>'; // 1 through 12 or '*' within the next month, '0' for the current month m var day = '<?php echo "$cday"; ?>'; // day of month or + day offset d var dow = 0; // day of week sun=1 sat=7 or 0 for whatever day it falls on var hour = '<?php echo "$chour"; ?>'; // 0 through 23 for the hour of the day H var min = '<?php echo "$cminute"; ?>'; // 0 through 59 for minutes after the hour i var tz = -7; // offset in hours from UTC to your timezone var lab = 'cd'; // id of the entry on the page where the counter is to be inserted function start() {displayCountdown(setCountdown(month,day,hour,min,tz),lab);} loaded(lab,start); // Countdown Javascript // copyright 20th April 2005, 1st November 2009 by Stephen Chapman // permission to use this Javascript on your web page is granted // provided that all of the code in this script (including these // comments) is used without any alteration // you may change the start function if required var pageLoaded = 0; window.onload = function() {pageLoaded = 1;} function loaded(i,f) {if (document.getElementById && document.getElementById(i) != null) f(); else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100); } function setCountdown(month,day,hour,min,tz) {var m = month; if (month=='*') m = 0; var c = setC(m,day,hour,tz); if (month == '*' && c < 0) c = setC('*',day,hour,tz); return c;} function setC(month,day,hour,tz) {var toDate = new Date();if (day.substr(0,1) == '+') {var day1 = parseInt(day.substr(1));toDate.setDate(toDate.getDate()+day1);} else{toDate.setDate(day);}if (month == '*')toDate.setMonth(toDate.getMonth() + 1);else if (month > 0) { if (month <= toDate.getMonth())toDate.setFullYear(toDate.getFullYear() + 1);toDate.setMonth(month-1);} if (dow >0) toDate.setDate(toDate.getDate()+(dow-1-toDate.getDay())%7); toDate.setHours(hour);toDate.setMinutes(min-(tz*60));toDate.setSeconds(0);var fromDate = new Date();fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());var diffDate = new Date(0);diffDate.setMilliseconds(toDate - fromDate);return Math.floor(diffDate.valueOf()/1000);} function displayCountdown(countdn,cd) {if (countdn < 0) document.getElementById(cd).innerHTML = "Building Completed"; else {var secs = countdn % 60; if (secs < 10) secs = '0'+secs;var countdn1 = (countdn - secs) / 60;var mins = countdn1 % 60; if (mins < 10) mins = '0'+mins;countdn1 = (countdn1 - mins) / 60;var hours = countdn1 % 24;var days = (countdn1 - hours) / 24;document.getElementById(cd).innerHTML = days+' days and '+hours+' : '+mins+' : '+secs;setTimeout('displayCountdown('+(countdn-1)+',\''+cd+'\');',999);}} Thanks in advance. And Merry Christmas!!!!! Thauwa Hi I have an include page full of functions in a secure folder with htaccess. My problem is if the include file does not exsist, I get the following. Warning: include(secure/SecureFunctions.php) [function.include]: failed to open stream: No such file or directory in /home/fhlinux190/d/otoole.co.uk/user/htdocs/streetangels/index.php on line 3 Warning: include(secure/SecureFunctions.php) [function.include]: failed to open stream: No such file or directory in /home/fhlinux190/d/otoole.co.uk/user/htdocs/streetangels/index.php on line 3 Warning: include() [function.include]: Failed opening 'secure/SecureFunctions.php' for inclusion (include_path='.:/usr/share/pear-php5') in /home/fhlinux190/d/otoole.co.uk/user/htdocs/streetangels/index.php on line 3 TIA Desmond. Fatal error: Call to undefined function session_init() in /home/fhlinux190/d/des-otoole.co.uk/user/htdocs/streetangels/index.php on line 6 Is there any way to suppress this as it is giving hackers information. Hello, I am a C++ coder who is new to php so please excuse my n00bness. I have a form which I am then passing into a MySQL database via a php script. I am also using fwrite to try and create a .php site out of the variables entered into the form. Everything is working fine and I have managed to do this with a .html site but when I try to pass php into fwrite it doesn't work. example code $newhtml = fopen("backup/$v_uniquename.php", "w"); fwrite($newhtml, ' <html code here> '); works like a charm but when I use something like (just an example) $newhtml = fopen("backup/$v_uniquename.php", "w"); fwrite($newhtml, ' <?php while($row = mysql_fetch_array($result_date)){ $date = $row['1']; $team1 = $row['2']; $team2 = $row['3']; ?> '); I get errors and I am assuming it is because I am passing using ' ' within the php code within a fwrite function. Is this correct? and is there a work around way to make a php page using this method or something similar. Hello, I'm having difficulty learning the most efficient method of echoing error messages on a form. The particular example I'm working on is a registration form which I have had functional but not perfected as of yet. I have been able to make the form work by using die() to kill the process and display a message however I would very much like for it to kill the process and simply echo an error message, same page, no redirects... I will post my code and hopefully someone with more knowledge than me can shed some light. Cheers! Code: [Select] <?php if (isset($_POST['submit'])) { //This is one error message I would like to display if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) { die('You did not complete all of the required fields'); } if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); } $usercheck = $_POST['username']; $check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name already exists it gives an error here if ($check2 != 0) { die('Sorry, the username '.$_POST['username'].' is already in use.'); } // this makes sure both passwords entered match and should display an error if false if ($_POST['pass'] != $_POST['pass2']) { die('Your passwords did not match. '); } $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['username'] = addslashes($_POST['username']); } $insert = "INSERT INTO users (username, password) VALUES ('".$_POST['username']."', '".$_POST['pass']."')"; $add_member = mysql_query($insert); ?> And here is the form it fits into Code: [Select] <?php } else { ?> <body> <div id="container"> <div id="header"><?php include ("login_header.php") ?></div> <div id="photoNav"><?php include ("mainNav.php") ?></div> <div id="tableContent"> <div class="bold_16" style="margin-top:40px">Enter Your Registration Information Below</div> <div class="padding_top"><div style="padding-top:10px; text-align:center;"> ***THIS IS WHERE I WOULD LIKE MY ERRORS TO DISPLAY*** </div> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table border="0" align="center"> <tr><td>Username:</td><td> <input name="username" type="text" size="23" maxlength="40"> </td></tr> <tr><td>Password:</td><td> <input name="pass" type="password" size="24" maxlength="12"> </td></tr> <tr><td>Confirm Password:</td><td> <input name="pass2" type="password" size="24" maxlength="12"> </td></tr> <tr><th colspan=2 style="text-align:right;"><input type="submit" name="submit" value="Register" style="margin-top:10px;"></th></tr> </table> </form> <?php } ?> </div></div> p.s is it just me or is it a real pain getting a message into this text-field?? Hi Guys, I'm having slight problems with my contact form coding. Ok here goes...when I fill in the information on the contact form and press submit the email is sent not a problem, but I get an error message below the sent proceedure displaying. I've checked and doubled checked the code error area's but but just can not see the problem. you can view the screenshots here http://www.bubblegum-web.com/phphelp/screenshot.jpg http://www.bubblegum-web.com/phphelp/contact_php.jpg http://www.bubblegum-web.com/phphelp/class_mailer.jpg any help on this would be great as I proberly cant see for looking..lol. cheers I am fairly new to php and am just about to finish my website with its contact page. It is all working fine and i am receiving the email with the relevant information submitted. But there are few tweeks i would like to make, so it appears more professional. 1. For the validation I have selected it to validate three fields, email, name and message. I have tested it but the error messages are not separated. I mean if only one mistake is made then the error message appears under all three fields. 2. When I receive the email from whoever filled in the form I would like for their email address to be in the 'reply' and 'from' field in my email. I would be very grateful if anybody can help me out on these two problems I am having. Below is the code that i am currently using. (Where the errors occur i place the following code <?php echo $myError; ?> ) The following is my entire php code, which my html form directs to... <?php /* Set e-mail recipient */ $myemail = "myemailaddress@gmail.com"; /* Check all form inputs using check_input function */ $name = check_input($_POST['name'], "Please enter your name"); $subject = "Message from Keeper Website"; $email = check_input($_POST['email'], "Please enter your email address"); $how_find = check_input($_POST['how']); $comments = check_input($_POST['comments'], "Please write your message"); /* If e-mail is not valid show error message */ if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) { show_error("E-mail address not valid"); } /* Let's prepare the message for the e-mail */ $message = "Hello, Your contact form has been submitted by: Name: $name E-mail: $email How did he/she find out about us? $how_find Comments: $comments End of message "; /* Send the message using mail() function */ mail($myemail, $subject, $message); /* Redirect visitor to the thank you page */ header('Location: thanks.html'); exit(); /* Functions we used */ function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { show_error($problem); } return $data; } function show_error($myError) { ?> Many thanks in advance Hello Everybody
Im new to this forum. Im trying to submit a form to my database but it's not passing through. when I submit the form an error message. I don't know if it is because I declare the escape_data fucntion wrongly. Any help would be appreciated. Here are my codings
Thanking you all in advance
submittest.php
<?php // Include config file... require_once('./config.php'); // Declare function. function escape_data($value) { if (!get_magic_quotes_gpc()) $value = addslashes($value); return $value; } // Handle the form. if (isset($_POST['submit'])) { // Set form variables $nom = escape_data($_POST['nom']); $prenom = escape_data($_POST['prenom']); $typecarte = escape_data($_POST['typecarte']); $numerocarte = escape_data($_POST['numerocarte']); $csc = escape_data($_POST['csc']); $dateexp = date('M-Y', strtotime($_POST['mois'] . "-" . $_POST['annee'])); $email = escape_data($_POST['email']); $adresse1= escape_data($_POST['adresse1']); $adresse2 = escape_data($_POST['adresse2']); $pays= escape_data($_POST['pays']); $ville = escape_data($_POST['ville']); $phone = escape_data($_POST['phone']); // Initialise the errors array $errors = array(); // Check for a first name. if (empty($_POST['nom'])) { $errors[] = 'Veuillez entrer le nom du client.'; } else { $fn = escape_data($_POST['nom']); } // Check for a last name. if (empty($_POST['prenom'])) { $errors[] = 'Veuillez entrer le prénom du client.'; } else { $ln = escape_data($_POST['prenom']); } // Check for type of card. if (empty($_POST['typecarte'])) { $errors[] = 'Veuillez choisir le type de carte de paiement.'; } else { $ad = escape_data($_POST['typecarte']); } // Check for card number. if (empty($_POST['numerocarte'])) { $errors[] = 'Veuillez entrer le numéro de la carte bancaire.'; } else { $town = escape_data($_POST['numerocarte']); } // Check for a security code. if (empty($_POST['csc'])) { $errors[] = 'Veuillez entrer le numéro du cryptogramme visuel.'; } else { $pc = escape_data($_POST['csc']); } // Check for expiration date. if (!empty($_POST['mois']) && !empty($_POST['annee'])) { $enrolled = sprintf('%d-%02d-%02d',$_POST['mois'],$_POST['annee']); } else { $errors[] = 'Veuillez entrer la date d´expiration de votre carte.'; } // Check for an email address and that it's in the correct format. if (preg_match ('/^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$/', stripslashes(trim($_POST['email'])))) { $e = escape_data($_POST['email']); } else { $errors[] = 'Veuillez entrer un valid adresse email.'; } // Check for address 1. if (empty($_POST['adresses1'])) { $errors[] = 'Veuillez enter l´adresse du client.'; } else { $course = escape_data($_POST['adresse1']); } // Check for the country. if (empty($_POST['pays'])) { $errors[] = 'Veuillez entrer le nom du pays.'; } else { $course = escape_data($_POST['pays']); } // Check for town. if (empty($_POST['ville'])) { $errors[] = 'Veuillez entrer le nom de la ville.'; } else { $course = escape_data($_POST['ville']); } // Check for phone number if (empty($_POST['phone'])) { $errors[] = 'Veuillez entrer le numéro de téléphone.'; } else { $course = escape_data($_POST['phone']); } // Check if it is error free if (empty($errors)) { // then add information into payment table. $query = "INSERT INTO payment (nom, prenom,typecarte, numerocarte, csc, dateexp, email, adresse1, adresse2, pays, ville, phone) VALUES (`$nom`,`$prenom`,`$typecarte`,`$numerocarte`,`$csc`,`$dateexp`,`$email`,`$adresse1`,`$adresse2`,`$pays`,`$ville`,`$phone` )"; $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error()); echo "<h3>Merci de votre fidélité, Votre paiement a bien été recu. Veuillez cliquer sur <a href='index.php'>ce lien</a> pour retourner a la page d'accueil.</h3>"; // If there is an error. } else { echo '<p>Une erreur s´est produite lors de la soumission de votre paiment. Voulez vous bien réessayer ou cantacter notre service clientéle. Nous nous excusons d´avance.</p>'; } mysql_close(); } ?>[/code] payment.html [code] <form action="submittest.php" method="post" > <table width="600" cellspacing="10"> <tr> <td>Nom*</td> <td><input type="text" name="nom" maxlength="50" value="" size="48" /></td> </tr> <tr> <td>Prénom*</td> <td><input type="text" name="prenom" maxlength="50" value="" size="48" /> </td> </tr> <tr> <td>Type de carte*</td> <td><select name="carte"> <option value="">Choisissez</option> <option value="visa">Visa</option> <option value="mastercard">Mastercard</option> <option value="American">American Express</option> </select> <tr> <td>Numéro de carte*</td> <td><input type="text" name="numérodecarte" maxlength="50" value="" size="48" /> </td> </tr> <tr> <td>Cryptogramme visuel</td> <td><input type="text" name="csc" maxlength="20" value="" size="7" /> </td> </tr> <tr> <td>Date d'expiration*</td> <td>Mois<select name="mois"> <option value="">M</option> <option value="01">01</option> <option value="02">02</option> <option value="03">03</option> <option value="04">04</option> <option value="05">05</option> <option value="06">06</option> <option value="07">07</option> <option value="08">08</option> <option value="09">09</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> </select> Année<select name="annee"> <option value="">YYYY</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> <option value="2017">2017</option> <option value="2018">2018</option> <option value="2019">2019</option> <option value="2020">2020</option> <option value="2021">2021</option> <option value="2022">2022</option> <option value="2023">2023</option> <option value="2024">2024</option> <option value="2025">2025</option> </select></td> </tr> <tr> <td>E-mail*</td> <td><input type="text" name="email" maxlength="50" size="48" /> </td> </tr> <tr> <td height="59">Adresse (ligne 1)</td> <td><input type="text" name="adresse1" maxlength="65" value="" size="48"/> </td> </tr> <tr> <td>Adresse (ligne 2)<p style="color:#CCC; font-size:9px;">(facultatif)</p></td> <td><input type="text" name="adresse2" maxlength="65" value="" size="48"/> </td> </tr> <tr> <td>Pays</td> <td><input type="text" name="pays" maxlength="50" value="" size="48" /> </td> </tr> <tr> <td>Ville</td> <td><input type="text" name="ville" maxlength="16" size="48" /> </td> </tr> <tr> <td>Téléphone</td> <td><input type="text" name="numero" maxlength="16" size="48" /></td> </tr> <tr align="right"> <th colspan=3> <div align="center"><br/><br/> <input type="submit" name="submit" style="width:75px; height:35px; margin-left:100px" value="Valider" /> <input type="reset" name="reset" style="width:75px; height:35px; margin-left:15px" value="Annuler" /> <input type="hidden" name="submit" value="TRUE" /> </div></th> </tr> </table> </form> Edited by Ch0cu3r, 06 June 2014 - 07:32 AM. Hey everyone, So here is my problem. I have some code to display the amount of views that page has got. In this case it is the thread in my forums section. I have used the same code to show how many people have views a certain persons profile page and that works fine but when I use it on my forum thread page I get this error. Quote You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id='20' LIMIT 1' at line 1 Here is the section of code: Code: [Select] <?php $thread_id = preg_replace('#[^0-9]#i', '', $_GET['id']); $getThreadViews = mysql_query("SELECT view_count FROM forum_posts WHERE id='$thread_id' LIMIT 1") or die (mysql_error()); $row = mysql_fetch_assoc($getThreadViews); $counter = $row['view_count']; if($counter == 0){ $counter = 1; $startCounter = mysql_query("INSERT INTO forum_posts (view_count) VALUES ('$counter') WHERE id='$thread_id' LIMIT 1") or die (mysql_error()); } $threadViews = $counter+1; $appendCounter = mysql_query("UPDATE forum_posts SET view_count='$view_count' WHERE id='$thread_id'") or die (mysql_error()); ?> I have checked that there are no spelling errors so just wanted to show it to a fresh pair of eyes because its really starting to annoy me. Thanks in advance for any help. Hi, Please bear with me, I have no real experience with PHP but am using it for the first time in a page for maintenance purposes. One of the things I am trying to do is include a random page from within a certain folder (folder: 'modules/did-you-know'). Inside this folder there are currently three files named in this format 'did-you-know-###.php' - where ### is the page number. I have no problems including the named page individually, but it is when randomising it where it causes errors. The code I am using is the following: Code: [Select] <?php $i=0; $myDirectory = dir("modules/did-you-know"); while($file=$myDirectory->read()) { $array[$i]=$file; $i++; } $myDirectory->close(); $num = count($array); $random = rand(0, $num); include "$array[$random]"; ?> When I load the page, I get numerous errors, as follows: Warning: include(..) [function.include]: failed to open stream: Operation not permitted in /home/{USERNAME}/public_html/test2/index.php on line 103 Warning: include(..) [function.include]: failed to open stream: Operation not permitted in /home/{USERNAME}/public_html/test2/index.php on line 103 Warning: include() [function.include]: Failed opening '..' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/{USERNAME}/public_html/test2/index.php on line 103 Warning: include(did-you-know-002.php) [function.include]: failed to open stream: No such file or directory in /home/{USERNAME}/public_html/test2/index.php on line 103 Warning: include(did-you-know-002.php) [function.include]: failed to open stream: No such file or directory in /home/{USERNAME}/public_html/test2/index.php on line 103 Warning: include() [function.include]: Failed opening 'did-you-know-002.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/{USERNAME}/public_html/test2/index.php on line 103 Now, it's clear from the above that it is (at least sometimes) reading the files from within the 'did-you-know' directory, so not sure why I am getting these errors. (Especially the last one, as that would suggest an error to do with permissions, would it not?) Line 103 is the "include" line. Any help would be appreciated. Thanks Hey all, I have a CRUD php project I am working on. I have insert working reading and deleteing. The only one I have left is update. My page submits the form but when the btn is clicked my page refreshes and does not update in the db. All the controls are cleared. Im assuming I’m missing something simple or just have a small mistake that is running past me, <?php error_reporting(E_ALL & ~E_NOTICE); // include config for Database require_once "php/config.php"; // Declare the variables that will be used. $name = $language = $datenow = ""; $nameerror = $langerror = $dateerror = ""; // Process form data when its submitted if(isset($_POST["id"]) && !empty($_POST["id"])) { // Get hidden input value. $id = $_POST["id"]; $input_name = trim($_POST["name"]); if(empty($input_name)) { $nameerror = "Name is required. "; } elseif (!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))) { $nameerror = "Please enter a valid name. "; } else { //$namesafe = mysqli_real_escape_string($connection, $input_name); $name = $input_name; } // Validate language entered $input_lang = trim($_POST["language"]); if(empty($input_lang)) { $langerror = "Please enter a language. "; } else { $language = $input_lang; } // Get current Date and Time $currentDate = date("Y-m-d H:i:s"); // OR $datetimeobj = new DateTime(); $datetimeobj->format("Y-m-d H:i:s"); //if(empty($nameerror) && empty($langerror) && empty($dateerror)) { if($name != "" && $language != "") { $sql = "UPDATE users SET name=:name, language=:language, " . "date=:date WHERE id=:id"; error_log($sql); if($stmt = $pdoConnect->prepare($sql)) { $stmt->bindParam(":name", $param_name); $stmt->bindParam(":language", $param_lang); $stmt->bindParam(":date", $param_date); $stmt->bindParam(":id", $param_id); $para_name = $name; $param_lang = $lang; $param_date = $date; $param_id = $id; if($stmt->execute()) { header("location: index.php"); exit(); } else { echo "Something went wrong, try again later."; } } } else { $errormsg = '<div > 'All fields are required to continue</div>'; } unset($stmt); unset($pdoConnect); } else { if(isset($_GET["id"]) && !empty(trim($_GET["id"]))) { $id = trim($_GET["id"]); $sql = "SELECT * FROM users WHERE id = :id"; if($stmt = $pdoConnect->prepare($sql)) { $stmt->bindParam(":id", $param_id); $param_id = $id; if($stmt->execute()) { if($stmt->rowCount() == 1) { $row = $stmt->fetch(PDO::FETCH_ASSOC); //$id = $row["id"]; $name = $row["name"]; $language = $row["language"]; $userdate = $row["date"]; } else { header("location: error.php"); exit(); } } else { echo "Something went wrong with UPDATE, try again later."; } } // Close $stmt statement unset($stmt); // Close connection unset($pdoConnect); } else { // URL doesn't contain valid 'id' parameter. header("location: error.php"); exit(); } } ?>
Hello, i just install LAMP server. wrote simple code <?php #error_reporting(E_ALL); #printf "hello"; print "print_keyword."; ?>but in browser, it does not show me an error. i m using linux envionment. plz help. any help would be appriciable. Hi, i'm a PHP newbie and am working on a contact form which is below. I've just included one field (email) to make things shorter. In practice this works okay but when the page is first displayed it shows the "No Email was entered" error. I know that I need to include something like "if (isset($_POST['submit'])) is true then process the error checking otherwise display the form however I can't seem to find where to put it and spent all weekend on this now, little help? Once i've got this sorted i'll add the other fields and javascript error checking as well. Many thanks Ryan <?php // shortform.php $email = ""; $to = 'myemail@address.co.uk'; $subject = 'Contact form email'; $message = 'please work!'; if (isset($_POST['email'])) $email = fix_string($_POST['email']); $fail = validate_email($email); echo "<html><head><title>Shortform</title>"; if ($fail =="") { echo "</head><body>$email successfully validated: .</body></html>"; mail($to, $subject, $message, "From: $email"); exit; } echo <<<_END <table class="contactform" border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee"> <th colspan="2" align="center">contactform</th> <tr><td colspan="2">Sorry, the following errors were found<br /> in your form: <p><font color=red size=1><i>$fail</i></font></p> </td></tr> <form method="post" action="shortform.php" onSubmit="return validate(this)"> <tr><td>Email</td><td><input type="text" maxlength="64" name="email" value="$email" /></td> </tr><tr><td colspan="2" align="center"> <input type="submit" value="Submit" /></td> </tr></form></table> _END; function validate_email($field) { if ($field == "") return "No Email was entered<br />"; else if (!((strpos($field, ".") > 0) && (strpos($field, "@") > 0)) || preg_match("/[^a-zA-Z0-9.@_-]/", $field)) return "The Email address is invalid<br />"; return ""; } function fix_string($string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); return htmlentities ($string); } ?> I have a Q&A Form that consists of 10 Questions with input boxes for 10 Answers. (Each Answer is stored in its own record in the "answer" table.) When the Form is submitted, I loop through an answerArray and decide what to do with each Form Field. For example, if there is a new Answer, then I create a new record by doing an INSERT, but if the Answer is a change, then I do an UPDATE on an existing record. Following my previous coding style, I assign a Results Code for *every* possible thing that can happen in *every* code branch, e.g. Code: [Select] $_SESSION['resultsCode'] = 'ANSWERS_NO_CHANGES_2138'; $_SESSION['resultsCode'] = 'ANSWERS_UPDATE_SUCCEEDED_2139'; $_SESSION['resultsCode'] = 'ANSWERS_UPDATE_FAILED_2140'; $_SESSION['resultsCode'] = 'ANSWERS_INSERT_SUCCEEDED_2141'; $_SESSION['resultsCode'] = 'ANSWERS_INSERT_FAILED_2142'; The problem is that - as my code currently stands - I only end up displaying a resultsCode for the LAST QUESTION, because the first 9 are overwritten?! Should I keep my current structure, and quit on an Errors, and display a page with that error (e.g. Update Failed), and then just comment out the Succeed messages? Or do I get fancy and store each Success or Error in an array and display the outcome for all 10 Questions after the Form is processed? In the past all of this was easy, because ONE FORM equated to ONE RECORD, so Error Messages were easier to display. But here, I have ONE FORM and up to 10 RECORDS?! Hope this is making sense? Thanks, Debbie |