PHP - Validate That All Fields In A Form Have A Value
Hello. So I already know an extremely elementary way to check to see if a form field is blank using PHP. For example:
Code: [Select] if ($subject == "") The question I have is, is there a way to have php check every field in a form to make sure it has some sort of value? I want to create an 'if' statement which basically says, "If all form fields have something filled in, then do this" For example Code: [Select] if ($subject == "any value") & ($name == "any value") & ($comment == "any value") Not sure if that makes sense. Any help would be greatly appreciated!!! Similar TutorialsHello, i need to validate 200 input fields if they are not empty, i have the following code where i'm stuck and i'm missing something any help is appreciated Code: [Select] if($_SERVER['REQUEST_METHOD'] == 'POST') { //print_r($_POST); foreach ($_POST as $value) { if (empty($value)){ echo 'empty'; } else { echo 'notempty'; } } } I need to validate the POST fields below except a few hidden inputs like User_id & category: They are not huge but i would not like to write for each a line of code like if(empty($_popst['field'])) ... How can simplify this by checking only if they are empty and display a message that lists all fields that were not filled? Code: [Select] array('user_id'=>$data['Id'], 'surname'=>$_POST['surname'], 'firstname'=>$_POST['firstname'], 'middlename'=>$_POST['middlename'], 'id_number'=>$_POST['id_number'], 'pin_number'=>$_POST['pin_number'], 'street'=>$_POST['street'], 'estate'=>$_POST['estate'], 'hse_number'=>$_POST['hse_number'], 'town'=>$_POST['town'], 'tele'=>$_POST['tele'], 'mobi'=>$_POST['mobi'], 'work_street'=>$_POST['work_street'], 'work_building'=>$_POST['work_building'], 'company'=>$_POST['company'], 'work_town'=>$_POST['work_town'], 'work_tele'=>$_POST['work_tele'], 'work_fax'=>$_POST['work_fax'], 'cont_surname'=>$_POST['cont_surname'], 'cont_firstname'=>$_POST['cont_firstname'], 'cont_middlename'=>$_POST['cont_middlename'], 'cont_street'=>$_POST['cont_street'], 'cont_building'=>$_POST['cont_building'], 'cont_company'=>$_POST['cont_company'], 'cont_home_tele'=>$_POST['cont_home_tele'], 'cont_office_tele'=>$_POST['cont_office_tele'], 'cont_mobi'=>$_POST['cont_mobi']); Hi I'm currently having a problem with my form. Users submit an empty field into the database and the next time another user tries to enter it just says username has been taken. I need some help on how to confirm that the username and email field isnt empty when inserted and that the email address is in the correct format.
<?php include "base.php"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>User Management System (Tom Cameron for NetTuts)</title> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div id="main"> <?php $username = mysql_real_escape_string($_POST["username"]); $email = mysql_real_escape_string($_POST["email"]); $mxitid = mysql_real_escape_string($_SERVER["HTTP_X_MXIT_USERID_R"]); if(!isset($mxitid)) { $mxitid = "DEFAULT"; } $checkusername = mysql_query("SELECT * FROM Users WHERE mxitid = '".$mxitid."'"); $checkemail = mysql_query("SELECT * FROM Users WHERE email = '".$email."'"); if(mysql_num_rows($checkusername) == 1) { echo "<h1>Error</h1>"; echo "<p>Sorry, that username is taken. Please go <a href=\"register.php\">back</a>and try again.</p>"; } elseif(mysql_num_rows($checkemail) == 1) { echo "<h1>Error</h1>"; echo "<p>Sorry, that email is taken. Please go <a href=\"register.php\">back</a>and try again.</p>"; } elseif ($_POST["register"]) { $username = mysql_real_escape_string($_POST["username"]); if(!isset($mxitid)) $mxitid = mysql_real_escape_string($_SERVER["HTTP_X_MXIT_USERID_R"]); if(!isset($mxitid)) { $mxitid = "DEFAULT"; } $registerquery = mysql_query("INSERT INTO Users (Username,mxitid,email) VALUES('".$username."','".$mxitid."','".$email."')"); if($registerquery) { echo "<h1>Success</h1>"; echo "<p>Your account was successfully created. Please <a href=\"index9.php\">click here to start chatting</a>.</p>"; } } else { ?> <h1>Register</h1> <p>Please enter your details below to register.</p> <p>Keep it clean! or you might get banned!</p> <form method="post" action="register.php" name="registerform" id="registerform"> <fieldset> <label for="username">Username:<br> Using emoticons in your name won't work!</label><input type="text" name="username" id="username" /><br /> <label for="email">Email:<br>(We need your real one to be able to contact you!)<br> If you don't have one make use of your mxit email service.</label><input type="email" name="email" id="email" /><br /> <input type="hidden" name="mxitid" id="mxitid" value="<? $_SERVER['HTTP_X_MXIT_USERID_R']; ?>"/><br /> <input type="submit" name="register" id="register" value="Register" /> </fieldset> </form> <?php } ?> </div> </body> </html>I tried using function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { die($problem); } return $data; }but it didnt seems to work Is jquery/Ajax better than real/raw PHP for form validation ?! What if JavaScript is turned off on the browser?! why after someone refreshing a page on the browser, the variables used to echo error after invalid data is being submitted will return the undefined variables error?! And how to handle form validation including an empty form field, maximum amount of value entered and so on How do I make email, name and phone required fields? thanks in advance <?php $email = $_POST['email']; $name = trim($_POST['name']); $phone = trim($_POST['phone']); $time = trim($_POST['time']); $zipcode = trim($_POST['zipcode']); $date = trim($_POST['date']); $EmailTo = "myemail@somedomain.com"; $Subject = "form"; /// Add a subject $Body = ""; $Body .= "Full name:\n$name\n\n"; $Body .= "Primary phone:\n$phone\n\n"; $Body .= "time:\n$time\n\n"; $Body .= "Zip code:\n$zipcode\n\n"; $Body .= "date:\n$date\n\n"; if($Subject == NULL) {$Subject = "From $EmailFrom";} $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>"); if ($success){ header ('Location: confirm.html');} else{ echo "Error! Your e-mail was not sent!";} ?> how can i validate if email is being entered correctly in a form? i have the following code Code: [Select] <?php if(isset($_POST['Submit'])){ //NEED TO CHECK IF FIELDS ARE FILLED IN if( empty($_POST['email'])){ header("Location:Messages.php?msg=12"); exit(); } if( empty($_POST['name'])){ header("Location:Messages.php?msg=3"); exit(); } if( empty($_POST['pw1']) && (empty($_POST['pw2']))){ header( "Location:Messages.php?msg=4" ); exit(); } $name=$_POST['name']; $email=$_POST['email']; $pw1=$_POST['pw1']; $pw2=$_POST['pw2']; if("$pw1" !== "$pw2" ){ header( "Location:Messages.php?msg=5" ); exit(); } $ip = $_SERVER['REMOTE_ADDR']; //connect to the db server , check if uname exist include('config.php'); $query1=("Select * from user where email='$email'"); $result1= mysql_query($query1); $num1=mysql_num_rows($result1); if ($num1 > 0) {//Email already been used header( "Location:Messages.php?msg=11" ); exit(); }else{ $query=("Select * from user where uname='$name'"); $result= mysql_query($query); $num=mysql_num_rows($result); if ($num > 0) {//Username already exist header( "Location:Messages.php?msg=6" ); exit(); }else{ //if username does not exist insert user details $query=( "INSERT INTO user (uname, pw,email,date_joined,ip,level) VALUES ('$name','$pw1','$email',NOW(),'$ip','Normal')"); if (@mysql_query ($query)) { header("location:login.php?reg=1"); exit; } } } mysql_close(); } ?> Hey Everyone, Im having trouble with this code, i'm trying to use preg_match to display an error when someone inputs their email and it doesnt have a specific domain (like for example yahoo.com). My logic is to use it as a filter, if the input doesnt have the word '@yahoo.com' it will show the error. What am I doing wrong? Code: [Select] if(preg_match("/^[a-zA-Z]\w+(\.\w+)*\@\yahoo.com", $data['email']) === 0) $err .= "• $lang[ERROR_DOMAIN]<br>"; Any help will be greatly appreciated. Thanks. - STG I want to make the form so only people with a specific email address can sign up to the site. So for example their ending email address was.... @something.apple.biz.com .. but to be accepted into the site, the email HAS to end with apple.biz.com. How could you validate it so it matches something specific like this. Here is my code at the moment which just checks that their is at least one . after the @ for it to be an acceptable email. If anyone could say what else to add to do this would be great if($email != '' && $register){ $emailcheck = explode("@", $email); $sql = "SELECT email FROM member WHERE email='$email'"; $query = mysql_query($sql); $emails = mysql_num_rows($query); if($emails != 0 ){ $alert .= '<p class="alert" style="clear:both;">That email address has already been registered</p>'; $register = false; }elseif(count($emailcheck) != 2){ $alert .= '<p class="alert" style="clear:both;">Please enter a valid email address</p>'; $register = false; }elseif(count($emailcheck) == 2){ $emailchecktwo = explode(".", $emailcheck[1]); if(count($emailchecktwo) < 2){ $alert .= '<p class="alert" style="clear:both;">Please enter a valid email address</p>'; $register = false; } } } Hi- the code below lets me upload a CSV file to my database if I have 1 field in my database and 1 column in my CSV. I need to add to my db "player_id" from the CVS file and "event_name" and "event_type" from the form... any ideas??? here's the code: Code: [Select] <?php $hoststring =""; $database = ""; $username = ""; $password = ""; $makeconnection = mysql_pconnect($hoststring, $username, $password); ?> <?php ob_start(); mysql_select_db($database, $makeconnection); $sql_get_players=" SELECT * FROM tabel ORDER BY player_id ASC"; // $get_players = mysql_query($sql_get_players, $makeconnection) or die(mysql_error()); $row_get_players = mysql_fetch_assoc($get_players); // $message = null; $allowed_extensions = array('csv'); $upload_path = '.'; //same directory if (!empty($_FILES['file'])) { if ($_FILES['file']['error'] == 0) { // check extension $file = explode(".", $_FILES['file']['name']); $extension = array_pop($file); if (in_array($extension, $allowed_extensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name'])) { if (($handle = fopen($upload_path.'/'.$_FILES['file']['name'], "r")) !== false) { $keys = array(); $out = array(); $insert = array(); $line = 1; while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) { foreach($row as $key => $value) { if ($line === 1) { $keys[$key] = $value; } else { $out[$line][$key] = $value; } } $line++; } fclose($handle); if (!empty($keys) && !empty($out)) { $db = new PDO( 'mysql:host=host;dbname=db', 'user', 'pw'); $db->exec("SET CHARACTER SET utf8"); foreach($out as $key => $value) { $sql = "INSERT INTO `table` (`"; $sql .= implode("`player_id`", $keys); $sql .= "`) VALUES ("; $sql .= implode(", ", array_fill(0, count($keys), "?")); $sql .= ")"; $statement = $db->prepare($sql); $statement->execute($value); } $message = '<span>File has been uploaded successfully</span>'; } } } } else { $message = '<span>Only .csv file format is allowed</span>'; } } else { $message = '<span>There was a problem with your file</span>'; } } ob_flush();?> <!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>CSV File Upload</title> </head> <body> <form class="form" action="" method="post" enctype="multipart/form-data"> <h3>Select Your File</h3> <p><?php echo $message; ?></p> <input type="file" name="file" id="file" size="30" /> <br/> <label>Event Name:</label><input name="event_name" type="text" value="" /> <br/> <label>Event Type:</label><input name="event_type" type="text" value="" /> <br/> <input type="submit" id="btn" class="button" value="Submit" /> </form> <br/> <h3>Results:</h3> <?php do { ?> <p><?php echo $row_get_players['player_id'];?></p> <?php } while ($row_get_players = mysql_fetch_assoc($get_players)); ?> </body> </html> Hi Guys i need help on a small matter. if you go to https://www.mywebchambers.co.uk/invoiceman/form.php when submitted all works ok. However if you delete rows 3, 4 and 5 and submit the page shows a value of 0.00 in the total column on rows 3, 4 and 5. How do i get this value removed so it is blank same as the rest ?
My form action is toolstation3.php code below
<!doctype html> <?php
{$orderno =($_POST["orderno"]);}
{$code3 =($_POST["code3"]);}
{$code4 =($_POST["code4"]);}
{$code5 =($_POST["code5"]);}
{$sum1 =($_POST["sum1"]);} {$nil =($_POST["nil"]);}
$net=$sum1+$sum2+$sum3+$sum4+$sum5;
$total=$net+$vat;
$sum1 = number_format($sum1, 2, '.', '');
if(empty($_POST['quantity3']) && empty($_POST['price3'])) {echo " $nil";}
echo "<br>   ____________________________________________________________________________________________________<br><br>"; echo "<H3>    Address                                                                                                                     Details "; echo "<br>   ___________________________________________________________          ____________________________________<br><br>";
echo "<tr>
echo "<tr> echo "<table cellpadding=3 border=0 style='float:left'>";
echo "<tr> echo "<table cellpadding=3 border=0 style='float:left'>";
echo "<tr> echo "<table cellpadding=3 border=0>";
echo "<tr> echo "<H3>    Items"; echo "<br>   __________________________________________<br><br>";
echo "<tr><th>Code</th><th>Name</th><th>Quantity</th><th>Price</th><th>Total</th><th>Vat Band</th></tr>"; echo "<tr><td>$code1</td><td>$name1</td><td>$quantity1</td><td>$price1</td><td>$sum1</td><td>$vatband1</td> "; echo "<tr><td>$code2</td><td>$name2</td><td>$quantity2</td><td>$price2</td><td>$sum2</td><td>$vatband2</td> "; echo "<tr><td>$code3</td><td>$name3</td><td>$quantity3</td><td>$price3</td><td>$sum3</td><td>$vatband3</td> "; echo "<tr><td>$code4</td><td>$name4</td><td>$quantity4</td><td>$price4</td><td>$sum4</td><td>$vatband4</td> "; echo "<tr><td>$code5</td><td>$name5</td><td>$quantity5</td><td>$price5</td><td>$sum5</td><td>$vatband5</td> ";
echo "<br>"; echo "<H3>    VAT Analysis"; echo "<br>   __________________________________________<br><br>"; echo "<table cellpadding=5 border=1>"; echo "<tr><th>Band</th><th>Rate</th><th>Net</th><th>VAT</th><th>Total</th></tr>"; echo "<tr><td>5</td><td>20%</td><td>$net</td><td>$vat</td><td>$total</td> ";
<div id="container">
I need help with a form .. My form needs to allow an additional drop down field for Groups. This form also needs to save the extra fields chosen into my MySQL DB. Here is my form.. Code: [Select] <form action='' method='post' class='assessment'> <h1>Create User</h1> <div class='label'>First Name</div> <div class='field'><input type='text' name='firstname' value='<?=$preUser->firstname?>' /></div> <div class='cb'></div> <div class='label'>Last Name</div> <div class='field'><input type='text' name='lastname' value='<?=$preUser->lastname?>' /></div> <div class='cb'></div> <div class='label'>Password</div> <div class='field'><input type='text' name='password' value='<?=$preUser->password?>' /></div> <div class='cb'></div> <div class='label'>Company</div> <div class='field'><input type='text' name='company' value='<?=$preUser->company?>' /></div> <div class='cb'></div> <div class='label'>Job Title</div> <div class='field'><input type='text' name='job' value='<?=$preUser->job?>' /></div> <div class='cb'></div> <div class='label'>Group Name</div> <div class='field'><select name='group'><?=$groupSelect?></select></div> <div class='cb'></div> <div class='label'>Address</div> <div class='field'><input type='text' name='street1' value='<?=$preUser->street1?>' /></div> <div class='cb'></div> <div class='label'>Address (optional)</div> <div class='field'><input type='text' name='street2' value='<?=$preUser->street2?>' /></div> <div class='cb'></div> <div class='label'>City</div> <div class='field'><input type='text' name='city' value='<?=$preUser->city?>' /></div> <div class='cb'></div> <div class='label'>State</div> <div class='field'><input type='text' name='state' value='<?=$preUser->state?>' /></div> <div class='cb'></div> <div class='label'>Postal Code</div> <div class='field'><input type='text' name='postal' value='<?=$preUser->postal?>' /></div> <div class='cb'></div> <div class='label'>Country</div> <div class='field'><input type='text' name='country' value='<?=$preUser->country?>' /></div> <div class='cb'></div> <div class='label'>Fax</div> <div class='field'><input type='text' name='fax' value='<?=$preUser->fax?>' /></div> <div class='cb'></div> <div class='label'>Phone</div> <div class='field'><input type='text' name='phone1' value='<?=$preUser->phone1?>' /></div> <div class='cb'></div> <div class='label'>Phone 2</div> <div class='field'><input type='text' name='phone2' value='<?=$preUser->phone2?>' /></div> <div class='cb'></div> <div class='label'>Email</div> <div class='field'><input type='text' name='email' value='<?=$preUser->email?>' /></div> <div class='cb'></div> <div class='label'>Website</div> <div class='field'><input type='text' name='website' value='<?=$preUser->website?>' /></div> <div class='cb'></div> <div class='label'>Photo</div> <div class='field imgupload'> <input type='hidden' name='photo' /> <? if( $preUser->photo ){ ?> <img src="../<?=$preUser->photo?>" style="height:300px; float:left;" /> <span class="rmimage" style="color:red; cursor:pointer; font-size:20px;padding-left:15px;" alt="<?=$preUser->photo?>">x</span> <? }else{ ?> <iframe src="../view/photo_upload.php" frameborder="0" scrolling="no" width="300" height="30"></iframe> <? } ?> </div> <div class='cb'></div> <div class='label'>Payment Option</div> <div class='field'> <input type='radio' name='payment' value='Pay' <? if( $preUser->payment == 'Pay' ) echo "checked='checked'"; ?> />Pay<br /> <input type='radio' name='payment' value='NonPaid' <? if( $preUser->payment == 'NonPaid' ) echo "checked='checked'"; ?> />NonPaid </div> <div class='cb'></div> <div class='label'>Dashboard Options</div> <div class='field'> <div><input type='checkbox' name='mysteps' <? if( $preUser->mysteps ) echo "checked='checked'"; ?> value='1' />My Steps</div> <div><input type='checkbox' name='mycalendar' <? if( $preUser->mycalendar ) echo "checked='checked'"; ?> value='1' />My Calendar</div> <div><input type='checkbox' name='myprofiles' <? if( $preUser->myprofiles ) echo "checked='checked'"; ?> value='1' />My Profile</div> <div><input type='checkbox' name='myplans' <? if( $preUser->myplans ) echo "checked='checked'"; ?> value='1' />My Plans</div> </div> <div class='cb'></div> <div class='submit_assessment'><input type='submit' name='create_user' class='submit' value='Create User' /> <input type='button' value='Back' class='back' name='admin_create' /></div> <div class='cb'></div> </form> <script> function setUploadedImage(flink){ $('.imgupload > input:first').after('<img src="../'+flink+'" style="height:300px; float:left;" /><span class="rmimage" style="color:red; cursor:pointer; font-size:20px;padding-left:15px;" alt="'+flink+'">x</span>'); $('.imgupload > iframe:first').remove(); $('.imgupload > input:first').val(flink); } $('.rmimage').live('click', function (){ $(this).prev().prev().val(''); $(this).prev().remove(); $(this).after('<iframe src="../view/photo_upload.php" frameborder="0" scrolling="no" width="300" height="30"></iframe>'); $.post('../ajax/admin.php',{remove_image:$(this).attr("alt")}); $(this).remove(); }); </script> the specific area in question is this... Code: [Select] <div class='label'>Group Name</div> <div class='field'><select name='group'><?=$groupSelect?></select></div> I need to be able to add another dropdown list to allow for multiple group selections that get saved into the DB once submitted. How do I go about doing this?????? I have got another of those problems that should be easy to solve but I cannot get my head round it! I have a form to enter data into a table and one of the fields can be left blank. However, I'd data is entered in the field it can be a Zero. This is leaving me a problem as I cannot find a way to get the script to insert NULL if the field is blank but actually put the Zero in if that is what is entered. I have tried several permutations of nested if's using empty or isset, but whatever I try, the same result is inserted in both scenarios. The arguments I need to pass are...... If field is empty INSERT null If field is 0 INSERT 0 If field is not empty and not 0 INSERT field Thanks in advance for any suggestions. Steve Is there anything wrong (or insecure) with using hidden form fields? I am working on a page where the user can choose one of 4 different subscription options. The approach I was going to use is to have a separate form for each plan, and when the user chooses one, submit a hidden form value so my script knows which subscription plan to grab out of the database. Thoughts? Good morning, I am a beginner at PHP, but trying to write a simple script to use at work and currently stuck on one part, looking for some advice! I have a simple form here > http://jmdostal.com/route2.php (Feel free to use it to test), that returns data on the next page, in a format such as : Jose F - Jose A - 285 Brenda L [Delivery] [Dallas] - Items Job 2 [Pickup] [Arlington] - Items [] [] - [] [] - [] [] - [] [] - [] [] - Gustavo - +1 - 284/pickup Jody W [Delivery] [Keller] - Items [] [] - [] [] - [] [] - [] [] - [] [] - [] [] - My question is how can I get it not to show the fields that are empty, so I dont have a bunch of lines with [] [] - formatting Here is my coding you can view here > http://jmdostal.com/code.txt A friend had suggested to me trying to use isset , so I tried it on a few lines, such as : if(isset($_POST['items14'])){ $items14 = "- ". Trim(stripslashes($_POST['items14'])); } But it didnt seem to change anything. Im sure this is something simply, Any suggestions are appreciated! Thanks ! Hello, A named field in an html form e.g. <input type="text" name="time"> is accessed as $_GET['time'] or $_POST['time'] by the processing script. What about an unnamed field like the one below: <input type="text" value="" id="1" /> How do I harvest this field's input as a variable from my php processing script? Thanks in advance The ID field doesn't display the data but it must be there because it was the key for the query. It is an int if that makes any difference. <html> <head> </head> <body> <?php // Connect to database===================================================== include("connect_db.php"); // retrieve form data ====================================================== $id = $_POST['id']; // sending query =========================================================== $query = "SELECT ama,model_name,model_mfg,wingspan,engine,decibels FROM airplanes WHERE id='$id'"; if( !$result = mysql_query($query) ) { echo "<br>Query $query<br>Failed with error: " . mysql_error() . '<br>'; } else { $fetch = mysql_fetch_array( $result ); } // Output form with retrieved data ========================================== ?> <h3>Change the data and then click the CHANGE button</h3><br> <form name="Form51" action="update_db_airplane.php" method="post"> ID #:<input type="text" name="id" value="<?=$fetch[id]?>" /><br> AMA #:<input type="text" name="ama" value="<?=$fetch[ama]?>" /><br> Model Name:<input type="text" name="model_name" value="<?=$fetch[model_name]?>" /><br> Model Mfg:<input type="text" name="model_mfg" value="<?=$fetch[model_mfg]?>" /><br> Wingspan:<input type="text" name="wingspan" value="<?=$fetch[wingspan]?>" /><br> Engine:<input type="text" name="engine" value="<?=$fetch[engine]?>" /><br> Decibels:<input type="text" name="decibels" value="<?=$fetch[decibels]?>" /><br><br> <input name="submit" id="submit" value="CHANGE!" type="submit"> </form> <br> <body> </html> Hi I am learning PHP and working on a Contact Us page with a required fields. For some reason it works great for the name and email, but always says please enter your phone number. If you guys have a better way of doing this please let me know. Also if the email is sent successfully I want it to goto the page "success.html" this part works good though just need some help please Here is the form: Code: [Select] <form action="contact.php" method="post" id="contactform"> <ol> <li> <label for="name">Full Name <span class="red">*</span></label> <input id="name" name="name" class="text" /> </li> <li> <label for="email">Your email <span class="red">*</span></label> <input id="email" name="email" class="text" /> </li> <li> <label for="phone">Phone Number <span class="red">*</span></label> <input id="phone" name="phone" class="text" /> </li> <li> <label for="company">Company</label> <input id="company" name="company" class="text" /> </li> <li> <label for="topic">Subject<span class="red">*</span></label> <input id="topic" name="topic" class="text" /> </li> <li> <label for="comments">Message <span class="red">*</span></label> <textarea id="comments" name="comments" rows="6" cols="50"></textarea> </li> <li class="buttons"> <input type="image" name="imageField" id="imageField" src="images/send.gif" /> </li> </ol> </form> The PHP code I tried: Code: [Select] <?php // Pick up the form data and assign it to variables $name = check_input ($_POST['name'], "Please enter your name"); $email = check_input ($_POST['email'],"Please enter your email"); $phone = check_input ($_POST['phone'], "Please enter your phone number"); $company = $_POST['company']; $topic = check_input ($_POST['topic'], "Please enter your subject"); $comments = check_input ($_POST['comments'], "Please enter your message"); function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if (strlen($data) == 0) { die($problem); } else { return $data; } } // Build the email (replace the address in the $to section with your own) $to = 'email@email.com"'; $subject = "New message: $topic"; $message = "Email: $email \n Phone: $phone \n Company: $company \n $name said: $comments"; $headers = "From: $email"; // Send the mail using PHPs mail() function mail($to, $subject, $message, $headers); // Redirect header("Location: success.html"); ?> Hello, I'm using the following code to echo what fields have been left blank: if(isset($_POST['submit'])) { $emailconfirm = $_POST['emailconfirm']; $name = trim($_POST['name']); $visitor_email = trim($_POST['email']); $user_message = trim($_POST['message']); if(empty($name)){ $name1 .= "<br>Name is empty."; } if(empty($visitor_email)){ $email1 .= "<br>Email is empty."; } if(empty($user_message)){ $message1 .= "<br>User Message is empty."; } But what seems to happen, is once you submit the form with blank fields, the echo does show, however, when you click submit again, the form submits even though the fields were blank. Is their a way of blocking 'post' if the fields are blank? Thanks I have html form that looks like: <form method="post" action="?a=up"> ...some mysql query... while ($i = mysql_fetch_array($result)) { <input name="name[]" type="text" value="<?=$i['name'];?>" /> <input name="years[]" type="text" value="<?=abs($age);?>"/> <input name="to[]" type="checkbox" value="<?=$i['id'];?>" /> } <input name="" type="submit" value="go" /> </form> The problem I have is that I can not get the values of the form fields such as "name" and "years". I can only get a list of the ids (value of "to" checkbox). The php code looks like: $cnt = 0; for($p = 0; $p <= (sizeof($to)-1); $p++) { echo $to[$p].$name[$p].$years[$p]"<br>"; $cnt++; } $tm = array($cnt); What I'm doing wrong? Hello everyone I need your assitance a great deal, so I have a form which i submitted to a php file throug ajax and jquery. It is working A ok but I want to be able to submit it with javascript instead, so i don't load any lib. And it is now a problem. The method I use to get the form field names and values in jquery is so simple and dynamic hence if changes are made on the html form i don't have to edit my jquery file to effect the change ie in respect to changing the name of the fields or adding more fields. But I don't know to archieve this using javascript. So i want to post my jquery script, for you all my mighty programmers to assist me get a javascript Clone for me, thank you very much for Helping Jquery file $("form.ajax").on("submit", function(){ var that= $(this); that.find('[name]').each(function(index,value){ var that = $(this), name =that.attr('name'), value =that.val(); data[name]=value; }); return false;}); Now the above code is just my major focus of the script. What it does is that select the form with an ajax class attribute and run a function after the user submits the form. The var that get reference to the above form throug the (this) reference. Next i use find fuction to look through out the open and close of our form.ajax form for any element that has the name attribute and set it into array using the .each(function (index,value){}) this is my main focus how to ilterate through the form looking for name attribute and set my finding into array using javascript. The next that var reference to the find statement and then we steal the name attribute and value from our findings and set an array called data with the stolen name variable as its index n value attribute as its value. Thank you once more my aim again is with the find and array setting statement. |