PHP - My Validation Scripts Are Not Outputting The Errors To My Form Page, I Have Added The Scripts Of The Validation Page And The Form Page
Similar TutorialsWe have the page that the users enter the information, which shows as this in an html file: <!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"> <head> <title>Scholarship Form</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <link href="style.css" type="text/css" rel="stylesheet" /> </head> <?php ?> <body> <h1 style = "text-align:center">Scholarship Form</h1> <form name = "scholarship" action = "process_Scholarship.php" method = "post"> <p>First Name: <input type="text" name="fName" /></p> <p>Last Name: <input type="text" name="lName" /></p> <p><input type="reset" value="Clear Form" /> <input type="submit" name="Submit" value="Send Form" /> </form> </body> </html> and then the attached file, process_Scholarship.php is the file giving me trouble. We're supposed to be using advanced escaping techniques from our book, and that's when things got tricky. I know it's something silly but I just cant figure it out! Any help asap would be awesome!!!! i'm really sorry, if there is a word that makes you confused. Code: [Select] <?php $ip = $_SERVER['REMOTE_ADDR']; if($_POST['hapus']=='Hapus') { $qDelDetail = mysql_query("DELETE FROM tbl_u_pekerjaan WHERE id_u_pekerjaan = '".$_POST['id_u_pekerjaan']."'"); } ?> <!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=iso-8859-1" /> <title>Untitled Document</title> <style> .suggestion { position:absolute; background-color:#eee; border:1px solid #CCC; display: none; width:400px; } .suggestion ul{ margin : 0 ; padding : 5px 5px ; } .suggestion ul li{ padding-top : 2px ; cursor : pointer ; list-style : none ; } .suggestion ul li:hover{ cursor : pointer ; list-style : none ; color : red ; /*font-weight : bold ;*/ } #form1 #pagu1 { border: 1px solid #999999; height: 21px; width: 355px; } </style> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="border_all" height="34" bgcolor="#CCCCCC"><strong><img src="image/icon_1.png" align="absmiddle" width="22" height="22" /> Pemeliharaan Komputer </strong></td> </tr> <tr> <td><hr size="1" color="#999999" /></td> </tr> <tr> <td> <table width="100%" border="0" cellspacing="2" cellpadding="3"> <form id="form1" name="form1" method="post" action=""> <tr> <td width="30%">Tahun Anggaran</td> <td width="2%">:</td> <td width="68%"><select name="thn_anggaran" id="thn_anggaran"> <?php $thn_on = date("Y"); ?> <option value="<?=$thn_on;?>"><?=$thn_on;?></option> <?php for($i = 2000; $i <= $thn_on; $i++) { ?> <option value="<?=$i;?>"><?=$i;?></option> <?php } ?> </select></td> </tr> <tr> <td width="30%">Jenis Anggaran</td> <td width="2%">:</td> <td width="68%"><select name="id_jns_anggaran"> <?php include "conn_ra.php"; ?> <?php $qRea = mysql_query("SELECT * FROM tbl_jns_anggaran ORDER BY id_jns_anggaran ASC"); while($dtRea = mysql_fetch_array($qRea)) { ?> <option value="<?=$dtRea['id_jns_anggaran'];?>"><?=$dtRea['nm_jns_anggaran'];?></option> <?php } ?> </select></td> </tr> <tr> <td align="left" valign="top">Nama Program</td> <td align="left" valign="top">:</td> <td align="left" valign="top"><input type="text" id="kd_program" name="kd_program" size="8" onkeyup="javascript:suggestme('program');" autocomplete="off" /> <input type="text" id="nm_program" name="nm_program" size="50" onkeyup="javascript:suggestme('program');" autocomplete="off" /> <div id="suggestion_program" class="suggestion"></div></td> </tr> <tr> <td align="left" valign="top">Nama Kegiatan</td> <td align="left" valign="top">:</td> <td align="left" valign="top"><input type="text" id="kd_kegiatan" name="kd_kegiatan" size="8" onkeyup="javascript:suggestme('kegiatan');" autocomplete="off" /> <input type="text" id="nm_kegiatan" name="nm_kegiatan" size="50" onkeyup="javascript:suggestme('kegiatan');" autocomplete="off" /> <div id="suggestion_kegiatan" class="suggestion"></div></td> </tr> <tr> <td align="left" valign="top">Nama Sub Kegiatan</td> <td align="left" valign="top">:</td> <td align="left" valign="top"><input type="text" id="kd_sub_kegiatan" name="kd_sub_kegiatan" size="8" onkeyup="javascript:suggestme('sub_kegiatan');" autocomplete="off" /> <input type="text" id="nm_sub_kegiatan" name="nm_sub_kegiatan" size="50" onkeyup="javascript:suggestme('sub_kegiatan');" autocomplete="off" /> <div id="suggestion_sub_kegiatan" class="suggestion"></div></td> </tr> <tr> <td align="left" valign="top">MAK</td> <td align="left" valign="top">:</td> <td align="left" valign="top"><input type="text" id="kd_mak" name="kd_mak" size="8" onkeyup="javascript:suggestme('mak');" autocomplete="off" /> <input type="text" id="nm_mak" name="nm_mak" size="50" onkeyup="javascript:suggestme('mak');" autocomplete="off" /> <div id="suggestion_mak" class="suggestion"></div></td> </tr> <!-- <tr> <td align="left" valign="top"><strong>Pagu</strong></td> <td align="left" valign="top"><strong>:</strong></td> <td align="left" valign="top"><div id="pagu1"></div> <input name="pagu" type="text" id="pagu" size="60" maxlength="250" /></td> </tr> --> <tr> <td width="30%"> Komputer </td> <td width="2%">:</td> <td width="68%"><select name="id_inventaris" id="id_inventaris"> <?php include "conn.php"; if(isset($_POST['id_inventaris'])) { $qKomputer = mysql_query("SELECT a.id_inventaris, a.nmr_inventaris, a.merk, a.type, a.processor_type FROM v_inventaris a WHERE id_inventaris = '".$_POST['id_inventaris']."'"); $dtKomputer = mysql_fetch_array($qKomputer); ?> <option value="<?=$dtKomputer['id_inventaris']?>"><?=$dtKomputer['nmr_inventaris'];?> | <?=$dtKomputer['merk'];?> <?=$dtKomputer['type'];?> <?=$dtKomputer['processor_type'];?></option> <?php }else { ?> <option>-Pilih Komputer-</option> <?php } ?> <?php $qKomputer = mysql_query("SELECT a.id_inventaris, a.nmr_inventaris, a.merk, a.type, a.processor_type FROM v_inventaris a WHERE EXISTS ( SELECT b.id_inventaris FROM tbl_memiliki b WHERE a.id_inventaris = b.id_inventaris ) ORDER BY id_inventaris ASC"); while($dtKomputer = mysql_fetch_array($qKomputer)) { ?> <option value="<?=$dtKomputer['id_inventaris']?>"><?=$dtKomputer['nmr_inventaris'];?> | <?=$dtKomputer['merk'];?> <?=$dtKomputer['type'];?> <?=$dtKomputer['processor_type'];?></option> <? } ?> </select> </td> </tr> <tr> <td>Jenis Pemeliharaan </td> <td>:</td> <td><select name="id_jenis" id="id_jenis"> <?php include "conn.php"; if(isset($_POST['id_jenis'])) { $qJenis = mysql_query("SELECT * FROM tbl_jenis WHERE id_jenis = '".$_POST['id_jenis']."'"); $dtJenis = mysql_fetch_array($qJenis); ?> <option value="<?=$dtJenis['id_jenis'];?>"><?=$dtJenis['nm_jenis'];?></option> <?php }else { ?> <option>-Pilih Jenis Pemeliharaan-</option> <?php } ?> <?php $qJenis = mysql_query("SELECT * FROM tbl_jenis ORDER BY id_jenis ASC"); while($dtJenis = mysql_fetch_array($qJenis)) { ?> <option value="<?=$dtJenis['id_jenis'];?>"><?=$dtJenis['nm_jenis'];?></option> <? } ?> </select> </td> </tr> <tr> <td>No. Surat/Memo</td> <td>:</td> <td><input name="no_surat" type="text" id="no_surat" size="50" /></td> </tr> <tr> <td>Tanggal Surat/Memo </td> <td>:</td> <td><input name="tgl_surat" type="text" id="tgl_surat" size="10" value="<?=$_POST['tgl_surat'];?>" /> <script language="JavaScript" type="text/javascript"> new tcal ({ // form name 'formname': 'form1', // input name 'controlname': 'tgl_surat' }); </script></td> </tr> <tr> <td>Asal Surat </td> <td>:</td> <td><input name="asal_surat" type="text" id="asal_surat" size="50" /></td> </tr> <tr> <td>Penanggung Jawab Pemeliharaan </td> <td>:</td> <td><select name="nip" id="nip"> <?php if(isset($_POST['nip'])) { $qNip = mysql_query("SELECT * FROM tbl_pegawai WHERE nip = '".$_POST['nip']."'"); $dtNip = mysql_fetch_array($qNip); ?> <option value="<?=$dtNip['nip'];?>"><?=$dtNip['nama'];?></option> <?php }else { ?> <option>-Pilih Penanggung Jawab Pemeliharaan-</option> <?php } ?> <?php $qNip = mysql_query("SELECT * FROM tbl_pegawai ORDER BY nama ASC"); while($dtNip = mysql_fetch_array($qNip)) { ?> <option value="<?=$dtNip['nip'];?>"><?=$dtNip['nama'];?></option> <? } ?> </select> </td> </tr> <tr> <td>No. SPK/Kuitansi </td> <td>:</td> <td><input name="no_spk" type="text" id="no_spk" size="50" /></td> </tr> <tr> <td>Tanggal SPK/Kuitansi </td> <td>:</td> <td><input name="tgl_pemeliharaan" type="text" id="tgl_pemeliharaan" size="10" value="<?=$_POST['tgl_pemeliharaan'];?>" /> <script language="JavaScript" type="text/javascript"> new tcal ({ // form name 'formname': 'form1', // input name 'controlname': 'tgl_pemeliharaan' }); </script></td> </tr> <tr> <td align="left" valign="top">Nama Rekanan </td> <td align="left" valign="top">:</td> <td align="left" valign="top"><input name="nm_rekanan" value="<?=$_POST['nm_rekanan'];?>" type="text" id="nm_rekanan" size="35" /></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="Submit" value="Simpan" /></td> </tr> <?php if($_POST['Submit']=='Simpan') { // data sudah ada atau belum $qCr = mysql_query("SELECT id_pemeliharaan FROM tbl_pemeliharaan WHERE tgl_pemeliharaan = STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y') AND id_jenis = '".$_POST['id_jenis']."' AND nm_rekanan = '".$_POST['nm_rekanan']."' AND id_pemeliharaan = '".$_POST['id_pemeliharaan']."'"); $dtCr = mysql_num_rows($qCr); if($dtCr <= 0) { /* $qId = mysql_query("SELECT id_pemeliharaan FROM tbl_pemeliharaan ORDER BY id_pemeliharaan DESC"); $dtId = mysql_fetch_array($qId); $id_pemeliharaan = $dtId[0] + 1; $id_realisasi_anggaran = $dtId[0] + 1; $qInsertData = mysql_query("INSERT INTO tbl_pemeliharaan(id_pemeliharaan, id_inventaris, id_jenis, nip, tgl_input, tgl_pemeliharaan, nm_rekanan, no_surat, tgl_surat, asal_surat, no_spk) VALUES('".$id_pemeliharaan."', '".$_POST['id_inventaris']."', '".$_POST['id_jenis']."', '".$_POST['nip']."', CURRENT_DATE(), STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y'), '".$_POST['nm_rekanan']."', '".$_POST['no_surat']."', STR_TO_DATE('".$_POST['tgl_surat']."','%m/%d/%Y'), '".$_POST['asal_surat']."', '".$_POST['no_spk']."')")or die(mysql_error()); include "include/conn_ra.php"; $qInsertData = mysql_query("INSERT INTO tbl_realisasi_anggaran(thn_anggaran, id_jns_anggaran, kd_program, kd_kegiatan, kd_sub_kegiatan, kd_bas, tgl_realisasi) VALUES('".$_POST['thn_anggaran']."', '".$_POST['id_jns_anggaran']."', '".$_POST['kd_program']."', '".$_POST['kd_kegiatan']."', '".$_POST['kd_sub_kegiatan']."', '".$_POST['kd_bas']."', STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y'))")or die(mysql_error()); */ $qId = mysql_query("SELECT id_pemeliharaan FROM tbl_pemeliharaan ORDER BY id_pemeliharaan DESC"); $dtId = mysql_fetch_array($qId); $id_pemeliharaan = $dtId[0] + 1; include("conn_ra.php"); $kd_sub_sistem = "PMKOM-".$id_pemeliharaan; //kd sub sistem di sistem anggaran $queryAlokasi = "SELECT alokasi_anggaran FROM tbl_alokasi_anggaran WHERE thn_anggaran = '".$_POST['thn_anggaran']."' AND id_jns_anggaran = '".$_POST['id_jns_anggaran']."' AND kd_program = '".$_POST['kd_program']."' AND kd_kegiatan = '".$_POST['kd_kegiatan']."' AND kd_sub_kegiatan = '".$_POST['kd_sub_kegiatan']."' AND kd_bas = '".$_POST['kd_mak']."' AND pj_anggaran = 'Bagian Sistem Informasi'"; $qAlokasi = mysql_query($queryAlokasi); $dtAlokasi = mysql_fetch_array($qAlokasi); $queryRealisasi = "SELECT realisasi_anggaran FROM tbl_realisasi_anggaran WHERE thn_anggaran = '".$_POST['thn_anggaran']."' AND id_jns_anggaran = '".$_POST['id_jns_anggaran']."' AND kd_program = '".$_POST['kd_program']."' AND kd_kegiatan = '".$_POST['kd_kegiatan']."' AND kd_sub_kegiatan = '".$_POST['kd_sub_kegiatan']."' AND kd_bas = '".$_POST['kd_mak']."' AND pj_anggaran = 'Bagian Sistem Informasi'"; $qRealisasi = mysql_query($queryRealisasi); $dtRealisasi = mysql_fetch_array($qRealisasi); $sisaAnggaran = $dtAlokasi['alokasi_anggaran'] - $dtRealisasi['realisasi_anggaran']; $qInsertAnggaran = mysql_query("INSERT INTO tbl_realisasi_anggaran(thn_anggaran, id_jns_anggaran, kd_program, kd_kegiatan, kd_sub_kegiatan, kd_bas, kd_sub_sistem, pj_anggaran, tgl_realisasi) VALUES('".$_POST['thn_anggaran']."', '".$_POST['id_jns_anggaran']."', '".$_POST['kd_program']."', '".$_POST['kd_kegiatan']."', '".$_POST['kd_sub_kegiatan']."', '".$_POST['kd_mak']."', '".$kd_sub_sistem."', 'Bagian Sistem Informasi', STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y'))") or die(mysql_error()); mysql_close($link1); include("conn.php"); /* $qInsertData = mysql_query("INSERT INTO tbl_pemeliharaan(thn_anggaran, id_jns_anggaran, kd_program, kd_kegiatan, kd_sub_kegiatan, kd_bas, id_pemeliharaan, id_kendaraan, id_jenis, nip, tgl_input, tgl_pemeliharaan, nm_bengkel, no_surat, tgl_surat, asl_surat, no_spk, pagu) VALUES('".$_POST['thn_anggaran']."', '".$_POST['id_jns_anggaran']."', '".$_POST['kd_program']."', '".$_POST['kd_kegiatan']."', '".$_POST['kd_sub_kegiatan']."', '".$_POST['kd_mak']."','".$id_pemeliharaan."', '".$_POST['id_kendaraan']."', '".$_POST['id_jenis']."', '".$_POST['nip']."', CURRENT_DATE(), STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y'), '".$_POST['nm_bengkel']."', '".$_POST['no_surat']."', STR_TO_DATE('".$_POST['tgl_surat']."','%m/%d/%Y'), '".$_POST['asl_surat']."', '".$_POST['no_spk']."', '".$sisaAnggaran."')") or die(mysql_error()); */ if(empty($_POST['thn_anggaran']) OR empty($_POST['id_jns_anggaran']) OR empty($_POST['kd_program']) OR empty($_POST['kd_kegiatan']) OR empty($_POST['kd_sub_kegiatan'])OR empty($_POST['kd_mak'])OR empty($_POST['id_inventaris'])OR empty($_POST['id_jenis'])OR empty($_POST['no_surat'])OR empty($_POST['tgl_surat'])OR empty($_POST['asal_surat'])OR empty($_POST['nip'])OR empty($_POST['no_spk'])OR empty($_POST['tgl_pemeliharaan'])OR empty($_POST['nm_rekanan'])) { echo '<script>alert("Data masih ada yang kosong!");</script>'; echo '<html><head> <meta http-equiv="refresh" content="0;url=index.php?p=tambah_pemeliharaan"> </head></html>'; } elseif($qInsertData = mysql_query("INSERT INTO tbl_pemeliharaan(thn_anggaran, id_jns_anggaran, kd_program, kd_kegiatan, kd_sub_kegiatan, kd_bas, id_pemeliharaan, id_inventaris, id_jenis, nip, tgl_input, tgl_pemeliharaan, nm_rekanan, no_surat, tgl_surat, asal_surat, no_spk) VALUES('".$_POST['thn_anggaran']."', '".$_POST['id_jns_anggaran']."', '".$_POST['kd_program']."', '".$_POST['kd_kegiatan']."', '".$_POST['kd_sub_kegiatan']."', '".$_POST['kd_mak']."','".$id_pemeliharaan."', '".$_POST['id_inventaris']."', '".$_POST['id_jenis']."', '".$_POST['nip']."', CURRENT_DATE(), STR_TO_DATE('".$_POST['tgl_pemeliharaan']."','%m/%d/%Y'), '".$_POST['nm_rekanan']."', '".$_POST['no_surat']."', STR_TO_DATE('".$_POST['tgl_surat']."','%m/%d/%Y'), '".$_POST['asal_surat']."', '".$_POST['no_spk']."')") or die(mysql_error())) /*if($qInsertData) {*/ ?>{ <script type="text/javascript"> var answer = confirm("Input data berhasil, Lanjutkan ke uraian pekerjaan ?") if (answer) { window.location = "index.php?p=u_pekerjaan&id_pemeliharaan=<?=$id_pemeliharaan;?>"; } else{ window.location = "index.php?p=pemeliharaan"; } </script> } <? /*}else { echo ("<script> alert (\"Input data gagal dilakukan !!\");</script><br>"); echo "<html><head> <meta http-equiv='refresh' content='0;url=index.php?p=tambah_pemeliharaan'> </head></html>"; }*/ } else { echo ("<script> alert (\"Data yang dimasukkan sudah ada\");</script><br>"); echo "<html><head> <meta http-equiv='refresh' content='0;url=index.php?p=pemeliharaan'> </head></html>"; } } ?> </form> </table> </td> </tr> <tr> <td><hr size="1" color="#999999" /></td> </tr> </table> </body> </html> 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 ?> Been screwing around on Google for about 3 hours trying to find a tutorial on what I am trying to do with absolutely no luck! I am simply trying to get my test script to echo errors from an array when a form criteria does not validate. This is my final revision which is still not working! Can someone please tell me what I am doing wrong? No matter what I do, I can't get away from this error: Notice: Undefined variable: error in C:\wamp\www\php\form_validation.php on line 13 <?php $o = $error[]; // test echo $o; // test if(!preg_match('/[^0-9A-Za-z]/',$_POST['first_name'])) { $error[] = "Please enter a valid First Name"; ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> First Name:<br /> <input name="first_name" type="text" size="50" maxlength="50" /><br /><br /> <input type="submit" /><br /><br /> </form> Hello, I am doing a php registration form, file name is register.php Code: [Select] <?php include("config.php"); $submit = strip_tags($_POST['submit']); $username = strip_tags($_POST['user_box']); $password = md5(strip_tags($_POST['pass_box'])); $cpassword = md5(strip_tags($_POST['c_pass_box'])); $email = strip_tags($_POST['email_box']); $mobile = $_POST['mobile_box']; $ip = $_SERVER['REMOTE_ADDR']; $date = date('Y-m-d'); $time = date('h-i-s'); $i = 0; $checkusername = mysql_num_rows(mysql_query("SELECT * FROM members WHERE username='$username'")); $checkemail = mysql_num_rows(mysql_query("SELECT * FROM members WHERE email='$email'")); /* Validating username field */ if($username != NULL) { if (strlen($username) > 15 || strlen($username) < 6) { echo "<p>Username must be in range of 6 to 15 Characters.</p>"; } else { //check in DB if ($checkusername == 1) { echo "<p>Username already exist in database.</p>"; } else { $i++; } } } else { echo "<p>Username cannot be Blank</p>"; } /* ----------validating password field---------- */ if ($password != "d41d8cd98f00b204e9800998ecf8427e" || $cpassword != "d41d8cd98f00b204e9800998ecf8427e") { if ($password == $cpassword) { if (strlen($password) > 16 && strlen($password) < 4) { echo "<p>password must be in range of 4 to 16 Characters.</p>"; } else { $i++; } } else { echo "<p>Passwords do not match.</p>"; } } else { echo "<p>Password cannot be empty</p>"; } /* ----------Validating Passwords End---------- */ /* ----------Validating Email field Starts---------- */ if($email != NULL) { if($checkemail == 1) { echo "<p>Email already exist.</p>"; } else { $i++; } } else { echo "<p>Email field cannot be empty.</p>"; } /* ----------Validating Email fiend ends---------- */ /* ----------Validating Email field Starts---------- */ if($mobile != NULL) { if(strlen($mobile) >10) { echo "<p>Mobile cannot be more than 10 digits long</p>"; } else { $i++; } } else { echo "<p>Mobile field cannot be empty.</p>"; } /* ----------Validating Email fiend ends---------- */ if ($i == 4) { mysql_query("INSERT INTO members (username, password, email, mobile, ip, date, time) VALUES ('$username', '$cpassword', '$email', '$mobile', '$ip', '$date', '$time')"); echo "<p>Successful Registration Done !</p>"; } ?> <!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>Untitled Document</title> </head> <body> <form id="form1" name="form1" method="post" action=""> <table width="576" height="229" border="0"> <tr> <td width="139">Username :</td> <td colspan="2"><label for="user_box"></label> <input type="text" name="user_box" id="user_box" size="30" height="30" /> (Between 6 to 15 Characters)</td> </tr> <tr> <td>Password :</td> <td colspan="2"><label for="pass_box"></label> <input type="password" name="pass_box" id="pass_box" size="30" height="30" /> (Between 4 to 16 Characters)</td> </tr> <tr> <td>Confirm Password :</td> <td colspan="2"><label for="c_pass_box"></label> <input type="password" name="c_pass_box" id="c_pass_box" size="30" height="30" /></td> </tr> <tr> <td>Email Address :</td> <td colspan="2"><label for="email_box"></label> <input type="text" name="email_box" id="email_box" size="30" height="30" /></td> </tr> <tr> <td>Mobile No. :</td> <td colspan="2"><label for="mobile_box"></label> <input type="text" name="mobile_box" id="mobile_box" size="30" height="30" /> (10 Characters)</td> </tr> <tr> <td> </td> <td width="171"><input type="submit" name="submit" id="submit" value="Submit" /></td> <td width="252"><input type="reset" name="button2" id="button2" value="Reset" /></td> </tr> </table> </form> </body> </html> When I load page, it shows following errors before Username cannot be Blank Password cannot be empty Email field cannot be empty. Mobile field cannot be empty. What I want is on loading page i.e. before giving any inputs, it should not show any errors. Need help Hello Everyone, I'm not a programmer, so please bear with me. I have a form, and on submit, need for it to send the data 1. to formmail.cgi (a PERL script) that emails me the information and then 2. sends the data to a shopping cart script called phpcart.php I'm told the best way to do this, is to have the forms ACTION post to a php script, which executes the two scripts above. I imagine something like this: <?php send data to formmail.cgi. When finished send data to phpcart.php exit ?> I've installed a few PHP applications on my site, but writing code is beyond me. Can anyone help? I would surely appreciate it. James Hi everybody. So I tried to do some research on this and the answers I found were pretty complicated and hard for me (as a newbie) to understand. What I am trying to do is send the results of an HTML form (radio buttons) to more than one php script (currently name_BB1.php but I would also like to send it to name_2.php). Is there a simple way to do this? Is it even possible?
All I need to pass from the script is the name of the department chosen (Music Books or Video) and the first script uses that information to access related databases. However the second script also needs to know the name of the department originally chosen and I don't know how to get that variable over there without asking the user a second time.
HTML:
<form action="name_BB1.php" method="POST"> </p>Which database would you like to select?<br \><br \> <input type="radio" name="choice" value="Music" />I want music!<br \> <input type="radio" name="choice" value="Books" />Give me books!<br \> <input type="radio" name="choice" value="Video" />I want to see videos!<br \><br \> <input type="submit" value="submit"> </p> </form> Thanks! Hi. Me next question, is how to I send variable from one page to another page. Example: Form Page checks user inputed values, updates database then uses // Thank you Page $insertGoTo = "changepass.php"; header(sprintf("Location: %s", $insertGoTo)); to redirect users to Confirmation page. Confirmation page: Checks to make sure values where properly stored in datebase and says "YES IT WORKED" OR "NO, SOMETHING WENT WRONG" Current Code: <?php session_start(); ?> <?php $submit = $_POST['submit']; // Form Data $email = $_POST['email']; $password_old = $_POST['password_old']; $password_new = $_POST['password_new']; $password_new_con = $_POST['password_new_con']; $errorcount = 0; // Edit anything inbetween the " " for the display error message $errormsg['Email'] = "Email Entered is not in our database"; $errormsg['OldPass'] = "Old Password Entered is Incorrect. Please check your Email"; $errormsg['NewPass'] = "New Password must be between 6 and 32 characters"; $errormsg['NewPassCon'] = "New Passwords do not match."; $errormsg['SecCode'] = "Security Code is Invalid"; $errormsg['dbPass'] = "Invalide Email or activation code. Please Contact <a href='mailto:webmaster@fusionfashionhair.com?subject=Fusion Fashion Hair - Member Activation Error%20Request'>Admin</a>"; $errormsg['NoErr'] = "No Errors, Continue"; $errormsg['PlaceHold'] = ""; $errortrack[] = $errormsg['PlaceHold']; if ($_POST[submit]){ if ($errorstop = "go") { $errorstop="go"; while ($errorstop<>"stop") { //Check for security code if ($_SESSION[key]==$_POST[user_code]){ // echo "True - Continue 0"; // echo "<p>----------</p>"; $_SESSION[key]=''; } else { // echo "False - Stop 0"; $errortrack[] = $errormsg['SecCode']; $errorcount++; $errorstop="stop"; } // check for existance if (!checkEmail($email)) { // echo "False - Stop 1"; $errortrack[] = $errormsg['Email']; $errorcount++; $errorstop="stop"; } else { // echo "True - Continue 1"; // echo "<p>----------</p>"; } // check for existance if (strlen($password_old)>5) { // echo "True - Continue 2"; // echo "<p>----------</p>"; } else { // echo "False - Stop 2"; $errortrack[] = $errormsg['OldPass']; $errorcount++; $errorstop="stop"; } // check for existance if (strlen($password_new)>32||strlen($password_new)<6) { // echo "False - Stop 3"; $errortrack[] = $errormsg['NewPass']; $errorcount++; $errorstop="stop"; } else { // echo "True - Continue 3"; // echo "<p>----------</p>"; } // check for existance if ($password_new_con==$password_new) { // echo "True - Continue 4"; // echo "<p>----------</p>"; $errorstop="stop";//Get Out of loop } else { // echo "False - Stop 4"; $errortrack[] = $errormsg['NewPassCon']; $errorcount++; $errorstop="stop"; } }//End While Loop // Check database require('dbConfig.php'); // Encrypts old password to check with Database Encryped Password $password_old = md5($password_old); $check = mysql_query("SELECT * FROM {$usertable} WHERE email='$email' AND password='$password_old'"); $checknum = mysql_num_rows($check); if ($checknum==1) { // echo "True - Continue 5 Set password"; // echo "<p>----------</p>"; // Encrypts new password $password = md5($password_new); //run a query to update the account $acti = mysql_query("UPDATE {$usertable} SET password='$password' WHERE email='$email'"); } else { // echo "False - Stop 5"; $errortrack[] = $errormsg['dbPass']; $errorcount++; $errorstop="stop"; }//End if checknum // echo "True - Continue 6 GO TO HEADER PAGE"; // Thank you Page $insertGoTo = "changepass.php"; header(sprintf("Location: %s", $insertGoTo)); } else { while($errorcount>=0) { // Test display all error messages // echo "<p>----------</p>"; // echo "<p>Error Count = '$errorcount'</p>"; } die ("PLEASE FILL IN ALL FIELDS"); } } ?> <?php // LINUX PLATFORM OPTION 3 // checkEmail function checks standard email format same as preg_match() // checkEmail function checks DSN records using checkdnsrr Use list() to seperate name and domain using split function // checkdnsrr ONLY WORKS on LINUX PLATFORM // Check to see if domain and username is active // uses fsockopen() to check if its in use using port 25 function checkEmail($email) { // checks proper syntax if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email)) { // gets domain name list($username,$domain)=split('@',$email); // checks for if MX records in the DNS if(!checkdnsrr($domain, 'MX')) { return false; } return true; } return false; } ?> I have noticed 2 script errors on my site within the .php files but can't see why they're occurring. The first appears at the bottom of my wordpress admin page:
Notice: Array to string conversion in /home/orkwine/public_html/test/wp-includes/class.wp-scripts.php on line 123
This is the area in that file:
`$srce = apply_filters( 'script_loader_src', $src, $handle ); if ( $this->in_default_dir($srce) ) { $this->print_code .= $this->print_extra_script( $handle, false ); $this->concat .= "$handle,"; $this->concat_version .= "$handle$ver"; return true; } else { $this->ext_handles .= "$handle,"; $this->ext_version .= "$handle$ver"; } }` Line 123 is: $this->ext_version .= "$handle$ver"; The other error i am getting is: Notice: Undefined index: prettyPhoto in /home/orkwine/public_html/test/wp-includes/class.wp-scripts.php on line 185 Notice: Trying to get property of non-object in /home/orkwine/public_html/test/wp-includes/class.wp-scripts.php on line 185 These are lines 183-194 in that file:` function set_group( $handle, $recursion, $group = false ) { if ( $this->registered[$handle]->args === 1 ) $grp = 1; else $grp = (int) $this->get_data( $handle, 'group' ); if ( false !== $group && $grp > $group ) $grp = $group; return parent::set_group( $handle, $recursion, $grp ); }` Line 185 is: if ( $this->registered[$handle]->args === 1 ) Can anyone help solve these errors? The full file can be seen he http://pastebin.com/spBAhuHf Here is a link to one of the pages in the website which shows the second error. http://test.orkneywi...-borealis-35cl/ Can anyone help with this? I 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> Quesion: Show each movie in the database on its own page, and give the user links in a "page 1, Page 2, Page 3" - type navigation system. Hint: Use LIMIT to control which movie is on which page. I have provided 3 files: 1st: configure DB, 2nd: insert data, 3rd: my code for the question. I would appreciate the help. I am a noob by the way. First set up everything for DB: <?php //connect to MySQL $db = mysql_connect('localhost', 'root', '000') or die ('Unable to connect. Check your connection parameters.'); //create the main database if it doesn't already exist $query = 'CREATE DATABASE IF NOT EXISTS moviesite'; mysql_query($query, $db) or die(mysql_error($db)); //make sure our recently created database is the active one mysql_select_db('moviesite', $db) or die(mysql_error($db)); //create the movie table $query = 'CREATE TABLE movie ( movie_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, movie_name VARCHAR(255) NOT NULL, movie_type TINYINT NOT NULL DEFAULT 0, movie_year SMALLINT UNSIGNED NOT NULL DEFAULT 0, movie_leadactor INTEGER UNSIGNED NOT NULL DEFAULT 0, movie_director INTEGER UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (movie_id), KEY movie_type (movie_type, movie_year) ) ENGINE=MyISAM'; mysql_query($query, $db) or die (mysql_error($db)); //create the movietype table $query = 'CREATE TABLE movietype ( movietype_id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, movietype_label VARCHAR(100) NOT NULL, PRIMARY KEY (movietype_id) ) ENGINE=MyISAM'; mysql_query($query, $db) or die(mysql_error($db)); //create the people table $query = 'CREATE TABLE people ( people_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, people_fullname VARCHAR(255) NOT NULL, people_isactor TINYINT(1) UNSIGNED NOT NULL DEFAULT 0, people_isdirector TINYINT(1) UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (people_id) ) ENGINE=MyISAM'; mysql_query($query, $db) or die(mysql_error($db)); echo 'Movie database successfully created!'; ?> ******************************************************************** *********************************************************************** second file to load info into DB: <?php // connect to MySQL $db = mysql_connect('localhost', 'root', '000') or die ('Unable to connect. Check your connection parameters.'); //make sure you're using the correct database mysql_select_db('moviesite', $db) or die(mysql_error($db)); // insert data into the movie table $query = 'INSERT INTO movie (movie_id, movie_name, movie_type, movie_year, movie_leadactor, movie_director) VALUES (1, "Bruce Almighty", 5, 2003, 1, 2), (2, "Office Space", 5, 1999, 5, 6), (3, "Grand Canyon", 2, 1991, 4, 3)'; mysql_query($query, $db) or die(mysql_error($db)); // insert data into the movietype table $query = 'INSERT INTO movietype (movietype_id, movietype_label) VALUES (1,"Sci Fi"), (2, "Drama"), (3, "Adventure"), (4, "War"), (5, "Comedy"), (6, "Horror"), (7, "Action"), (8, "Kids")'; mysql_query($query, $db) or die(mysql_error($db)); // insert data into the people table $query = 'INSERT INTO people (people_id, people_fullname, people_isactor, people_isdirector) VALUES (1, "Jim Carrey", 1, 0), (2, "Tom Shadyac", 0, 1), (3, "Lawrence Kasdan", 0, 1), (4, "Kevin Kline", 1, 0), (5, "Ron Livingston", 1, 0), (6, "Mike Judge", 0, 1)'; mysql_query($query, $db) or die(mysql_error($db)); echo 'Data inserted successfully!'; ?> ************************************************************** **************************************************************** MY CODE FOR THE QUESTION: <?php $db = mysql_connect('localhost', 'root', '000') or die ('Unable to connect. Check your connection parameters.'); mysql_select_db('moviesite', $db) or die(mysql_error($db)); //get our starting point for the query from the URL if (isset($_GET['offset'])) { $offset = $_GET['offset']; } else { $offset = 0; } //get the movie $query = 'SELECT movie_name, movie_year FROM movie ORDER BY movie_name LIMIT ' . $offset . ' , 1'; $result = mysql_query($query, $db) or die(mysql_error($db)); $row = mysql_fetch_assoc($result); ?> <html> <head> <title><?php echo $row['movie_name']; ?></title> </head> <body> <table border = "1"> <tr> <th>Movie Name</th> <th>Year</th> </tr><tr> <td><?php echo $row['movie_name']; ?></td> <td><?php echo $row['movie_year']; ?></td> </tr> </table> <p> <a href="page.php?offset=0">Page 1</a>, <a href="page.php?offset=1">Page 2</a>, <a href="page.php?offset=2">Page 3</a> </p> </body> </html> Some code from my pages ,
Page1 ( Redirecting page )
<html> <title>login_redirect.</title> body> <form name="redirect" action="http://mysite/page2.php" method="post"> <input type="hidden" name="mac" value="$(mac)"> </form> <script language="JavaScript"> <!-- document.redirect.submit(); //--> </script> </body> </html>Page 2 ( select product ) <?php session_start(); ini_set('display_errors',1); error_reporting(E_ALL); include '../lib/config.php'; include '../lib/opendb.php'; // get user mac adres from redirect post page1 $_SESSION['macid'] = $_POST['mac']; // set $macid for other use ( maybe not needed, am learning ) $macid = $_SESSION['macid']; // echo $macid does show mac adress, so variable is not empty here if (!empty($_POST["submit"])) { $product_choice = $_POST['accounttype']; $query= "SELECT AccountIndex, AccountCost, AccountName FROM AccountTypes WHERE AccountIndex='$product_choice'"; $result = mysql_query($query) or die('Query failed. ' . mysql_error()); while($row = mysql_fetch_array($result)) { $_SESSION['AccountIndex'] = $row['AccountIndex']; $_SESSION['AccountCost'] = $row['AccountCost']; $_SESSION['AccountName'] = $row['AccountName']; } header('Location: page3.php'); } // did leave out the other/html/form stuff herePage 3 ( show Session variables ) <?php ini_set('display_errors',1); error_reporting(E_ALL); session_start(); print_r($_SESSION); ?>Now, on page 3 i do see the right session varables, only the "macid" is empty. why ? Hi all, Im trying to add validation to a form to allow PHP to check before its sends the values to another page for them to be uploaded to a database. The problem i have is that i have taken a, i thought simple PHP validating script off the net and i cant seem to get it to work, its just giving me a blank page. I dont know if the script is outdated, i dont think it is. The script is he Code: [Select] <?php include("validation.php"); ?> <!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>Test Area</title> <link rel="stylesheet" href="test.css" type="text/css" media="screen" /> </head> <body> <div id="container"> <h1>Add a Product</h1> <?if(isset($_POST['send'])&amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;(!validateModel($_POST['model']) || !validatePrice($_POST['price']) || !validateDescription($_POST['description']) ) ):?> <div id="error"> <ul> <?if(!validateModel($_POST['model'])):?> <li><strong>Invalid Name:</strong> We want names with more than 3 letters!</li> <?endif?> <?if(!validatePrice($_POST['price'])):?> <li><strong>Invalid E-mail:</strong> Type a Valid Price!</li> <?endif?> <?if(!validateDescription($_POST['description'])):?> <li><strong>Invalid message:</strong> Type a message with at least with 10 letters</li> <?endif?> </ul> </div> <?elseif(isset($_POST['send'])):?> <div id="error" class="valid"> <ul> <li><strong>Congratulations!</strong> All fields are OK ;)</li> </ul> </div> <?endif?> <form method="post" id="customForm" action="" enctype="multipart/form-data"> <div> <label for="model">Model Number</label> <input id="model" name="model" type="text" /> <span id="modelInfo">Please enter your Product Model Number!</span> </div> <div> <label for="product">Product</label> <select class="products" name="products"> <option value="0">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> <span id="productInfo">Please choose a Product Title!</span> </div> <div> <label for="price">Price</label> <input id="price" name="price" type="text" /> <span id="priceInfo">Please enter a Price!</span> </div> <div> <label for="photo">Image</label> <input style="font-size:13px;" class="file" name="photo" type="file" /> <span id="photoInfo">Please choose an Image!</span> </div> <div> <label for="message">Description</label> <textarea id="description" name="description" cols="" rows=""></textarea> </div> <div> <input id="send" name="send" type="submit" value="Send" /> </div> </form> </div> </body> </html> This is the validation file: <?php function validateModel($model){ //if it's NOT valid if(strlen($model) < 4) return false; //if it's valid else return true; } function validatePrice($price){ //if it's NOT valid if(strlen($price) < 4) return false; //if it's valid else return true; } function validateDescription($description){ //if it's NOT valid if(strlen($description) < 10) return false; //if it's valid else return true; } ?> I can't spot the problem, any suggestions? Hello! I was wondering if I could have some help with some form validation. In my insert script, I have: <label for="text"><br /> <br /> Question Text:</label> <textarea name="text" id="text" cols="45" rows="5"> </textarea> Then in a separate script, I input the data into a database: $data = array('text' => $_POST['text'] 'question_type' => $_POST['question_type'], 'solution' => $_POST['solution'], 'author_id' => $_POST['author'], 'public_access' => $_POST['public_access']); In this database script, I'd like to check if the text field was "posted": if it's empty I'd then like to print "Required field" on my original script. First, if there's nothing to be posted from the text field, I want to stop the database script and return before entering a blank field into my database. Then, it would be great if I could print a "Required field" message in the original script. Thanks in advance for your help! I am asking for some simple help, please. :-) I have a form that I would like to validate very specific information on - without having it validate in the php and loose what the client just put into the site. I have found an example in this "validation" process. However, when I open this up in Dreamweaver CS4, I have an error on line 67 as a syntex error. I am unable to see where this would be. All I need is a verification on the name, the phone number, and the email address. Here is what I have so far.... **This is contact form** Code: [Select] <script language="JavaScript"> function checkForm() { var cname, cemail, cphone with(window.document.Contact1) { cname = name; cemail = EmailFrom; cphone = phone; } if(trim(cname.value) == '') { alert('Please enter your name'); cname.focus(); return false; } else if(trim(cemail.value) == '') { alert('Please enter your email'); cemail.focus(); return false; } else if(!isEmail(trim(cemail.value))) { alert('Email address is not valid'); cemail.focus(); return false; } else if(trim(cphone.value) == '') { alert('Please enter message subject'); csubject.focus(); return false; } } else { cname.value = trim(cname.value); cemail.value = trim(cemail.value); cphone.value = trim(cphone.value); return true; } } function trim(str) { return str.replace(/^\s+|\s+$/g,''); } function isEmail(str) { var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag| ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg| bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg| ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk| dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb| gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn| hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg| kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly| ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum| mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu| nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa| re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st| su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz| ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za| zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i; return regex.test(str); } </script> Below is the php file that I am using.... Code: [Select] <!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=iso-8859-1" /> <title>Emailing Form Data</title> </head> <body> <?php ini_set ("display_errors", "1"); error_reporting(E_ALL); //declaration of variables $EmailFrom = trim(stripslashes($_POST['EmailFrom'])); $EmailTo = "ornclo@aol.com"; $Subject = "Women United Contact"; $Name = trim(stripslashes($_POST['name'])); $Address = trim(stripslashes($_POST['address'])); $City = trim(stripslashes($_POST['city'])); $State = trim(stripslashes($_POST['state'])); $Phone1 = trim(stripslashes($_POST['phone1'])); $Phone2 = trim(stripslashes($_POST['phone2'])); $Phone3 = trim(stripslashes($_POST['phone3'])); $email = trim(stripslashes($_POST['email'])); foreach ($_POST['visit'] as $value) { $Church = trim(stripslashes($value)); } foreach ($_POST['hear'] as $hear) { $About = trim(stripslashes($hear)); } foreach ($_POST['help'] as $help) { $Ask = trim(stripslashes($help)); } $Comments = trim(stripslashes($_POST['comments'])); // validation $validationOK=true; if (($EmailFrom)=="") $validationOK=false; if (($Name)=="") $validationOK=false; if (($Phone1)=="") $validationOK=false; if (($Phone2)=="") $validationOK=false; if (($Phone3)=="") $validationOK=false; if (($email)=="") $validationOK=false; if (($Comments)=="") $validationOK=false; if (!$validationOK) { print "<meta http-equiv=\"refresh\" content=\"0;URL=WUerror.html\">"; exit; } // prepare email body text $Body = "\n"; $Body .= "Name: "; $Body .= $Name; $Body .= "\n"; $Body .= "Address: "; $Body .= $Address; $Body .= "\n"; $Body .= "City: "; $Body .= $City; $Body .= "\n"; $Body .= "State: "; $Body .= $State; $Body .= "\n"; $Body .= "Phone: "; $Body .= $Phone1; $Body .= "-"; $Body .= $Phone2; $Body .= "-"; $Body .= $Phone3; $Body .= "\n"; $Body .= "Attended Church of God?: "; $Body .= $Church; $Body .= "\n"; $Body .= "How did you hear about us?: "; $Body .= $About; $Body .= "\n"; $Body .= "What can we do to help you?: "; $Body .= $Ask; $Body .= "\n"; $Body .= "Comments: "; $Body .= $Comments; $Body .= "\n"; // send email $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>"); // redirect to success page if ($success){ print "<meta http-equiv=\"refresh\" content=\"0;URL=WUok.html\">"; } else{ print "<meta http-equiv=\"refresh\" content=\"0;URL=WUerror.html\">"; } ?> </body> </html> Unless there is a way to change this line: print "<meta http-equiv=\"refresh\" content=\"0;URL=WUerror.html\">"; to have it keep in the same window - or even possibly open a NEW window with the "error.html" - that would be fine as well. Again - when I open up Contact1.html in DW CS4, I get a syntext error on line 67. When I use just straight form, it opens to new window with php - > error.html, which in turns looses everything the client just typed. Any help is greatly appreciated and thank you in advance. Blessings! If asked, I can attach the files if needed as well, but the code is pretty self-explain. Hi all! Im trying to modify a script so that when a user submits data on a form if there are any errors it flags all errors and not just the first one the script comes to and 'dies'. Heres the form code <?php session_start(); ?> <!--//-----------------------------------------------------------------------------------------------+ | // Sample AJAX web form By: Codex-m | // http://www.php-developer.org | // You are free to use and improve this script provided you link to author web site: http://www.php-developer.org | //--------------------------------------------------------------------------------------------------------------> <html> <head> <title>Sample AJAX Web Form</title> <script type="text/javascript" src="prototype.js"></script> <script type="text/javascript"> function sendRequest() { new Ajax.Request("ajaxvalidate.php", { method: 'post', parameters: 'name='+$F('name')+'&phonenumber='+$F('phonenumber')+'&age='+$F('age')+'&captcha='+$F('captcha'), onComplete: showResponse }); } function showResponse(req){ $('show').innerHTML= req.responseText; } </script> <style type="text/css"> P.yellow {background-color: #ffff00;} </style> </head> <body> <h3>This is a sample PHP web form with AJAX validation</h3> Please complete the form below and then press "Submit button".<br /> <br /><br /> <form action="/ajaxwebform/ajaxvalidate.php" method="post" onsubmit="return false;"> Enter your Full Name, First name and Last name ONLY (Example: John Doe)<br /> <input style="background-color: #FFFFC0" type="text" name="name" id="name" size="50"> <br /><br /> Enter your Phone number (numbers only, no dashes and spaces)<br /> <input style="background-color: #FFFFC0" type="text" name="phonenumber" id="phonenumber" size="35"> <br /><br /> Enter your Age (Numbers only)<br /> <input style="background-color: #FFFFC0" type="text" name="age" id="age" size="50"> <br /><br /> <img src="/ajaxwebform/captcha.php" /> <br /> Enter the Captcha as shown above: <br /> <br /> <input style="background-color: #FFFFC0" type="text" name="captcha" id="captcha" size="10"> <br /> <br /> <input type="submit" value="Submit" onClick="sendRequest()"> </form> <br /> This form will validate your data entry using AJAX. If you are correct with your data entry, the entire information entered will be shown in this page without reloading. <br /> <br /><br /> <p class="yellow" id="show"></p> </body> </html> Heres the php validating code <?php session_start(); ?> <!--//-----------------------------------------------------------------------------------------------+ | // Sample AJAX web form By: Codex-m | // http://www.php-developer.org | // You are free to use and improve this script provided you link to author web site: http://www.php-developer.org | //--------------------------------------------------------------------------------------------------------------> <?php //start session to recover captcha answers //connect to database $username = "root"; $password = ""; $hostname = "localhost"; $database = "newdb"; $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); $selected = mysql_select_db($database,$dbhandle) or die("Could not select $database"); //extract form inputs $name =$_POST['name']; $phonenumber =$_POST['phonenumber']; $age =$_POST['age']; $usercaptchaanswer =$_POST['captcha']; $correctcaptcha = $_SESSION['answer']; //sanitize early for any possible MySQL entry $name = mysql_real_escape_string(stripslashes(trim($name))); $phonenumber = mysql_real_escape_string(stripslashes(trim($phonenumber))); $age = mysql_real_escape_string(stripslashes(trim($age))); $usercaptchaanswer = mysql_real_escape_string(stripslashes(trim($usercaptchaanswer))); $correctcaptcha = mysql_real_escape_string(stripslashes(trim($correctcaptcha))); Validate captcha entry if ($correctcaptcha != $usercaptchaanswer) { echo 'ERROR: You have entered wrong captcha code'; die (); } //Step 2 of data validation: check for blank entries if (empty($name)) { //name field is blank echo 'ERROR: The name field is empty.'; die (); } if (empty($phonenumber)) { //phone field is blank echo 'ERROR: The phone field is empty.'; die (); } if (empty($age)) { //age field is blank echo 'ERROR: The age field is empty.'; die (); } if (empty($usercaptchaanswer)) { captcha field is blank echo 'ERROR: The captcha field is empty.'; die (); } //Step 3 of data validation: Ensuring correct format //Step 3.1 validate full name, presence of first name and last name $mystring = $name; $findme = ' '; $pos = strpos($mystring, $findme); $actualposition =$pos + 1; //count strings $count =strlen($mystring); //count the number of characters for the first name $countfirstname = $actualposition - 1; //count the number of characters for the last name $countlastname = $count - $actualposition; //detect if full name has middle name $posmid= strpos($mystring,$findme,$actualposition) + 1; $middleadjust = $posmid - $actualposition; $purealpha = str_replace(" ", "x", $mystring); if ($actualposition==1) { echo 'ERROR: You either forgot your first name or your last name.'; die (); } if ($countfirstname <2) { echo 'ERROR: You are using an invalid first name, it should contain more than one character.'; die (); } if ($countlastname <2) { echo 'ERROR: You are using an invalid last name, it should contain more than one character.'; die (); } if ($middleadjust >= 2) { echo 'ERROR: You should not be using a middle name, please use only first name and last name.'; die (); } if (!(ctype_alpha($purealpha))) { echo 'ERROR: Full name can only consist of alphabetic characters.'; die (); } //Step 3.2 Validate phone number if (!(ctype_digit($phonenumber))) { echo 'ERROR: A phone number should consist of numerical digits only and no spaces between numbers'; die (); } //Step 3.3 Validate age if (!(ctype_digit($age))) { echo 'ERROR: Your age should consist of numerical digits only and no spaces between numbers'; die (); } //Step 4. If all data entry is correct, show results in another page, assigned all values to sessions echo 'Thank you for the correct data entry, below are the information entered:'; echo '<br />'; echo 'Your full name is: '.$name; echo '<br />'; echo 'Your phone number is: '.$phonenumber; echo '<br />'; echo 'Your age is: '.$age; echo '<br />'; echo '<a href="/ajaxwebform/ajaxwebformtest.php">Click here to enter another data.</a>'; $_SESSION = array (); session_destroy (); mysql_close($dbhandle); ?> Hi. I'm new to PHP and have a problem with some form validation. The code below is my contact form. It was working until I added a dropdown list and checkbox. For all the other fields I created an input variable using the 'name' attribute to reference the data entered into the input fields and the validation appeared to work and an email was sent to the appropriate email address. For the checkbox field I have also created a 'name' attribute but don't know whether this is right way to confirm whether the box has been checked? For the field with a dropdown selection I have used the option 'selected', but again, don't know whether this is right or not. Now when I enter valid data into all the fields, select a value from the dropdown and check the checkbox, I get an error message stating that I need to fill in all the form fields. I am pretty sure it is to do with the way I have tried to pick up the data from dropdown list and the checkbox, but can't figure out what it is. Any help would be much appreciated. Thanks in advance.
<?php echo file_get_contents('header.php'); ?> <?php // Message Vars $msg = ''; $msgClass = ''; // Check to see if the form has been submitted if(filter_has_var(INPUT_POST, 'submit')) { //Input Data Variables $firstname = htmlspecialchars($_POST['firstname']); $lastname = htmlspecialchars($_POST['lastname']); $phonenumber = htmlspecialchars($_POST['phonenumber']); $email = htmlspecialchars($_POST['email']); $selected = htmlspecialchars($_POST['selected']); $message = htmlspecialchars($_POST['message']); $checkbox = htmlspecialchars($_POST['checkbox']); //Check required fields if(!empty($firstname) && !empty($lastname) && !empty($phonenumber) && !empty($email) && !empty($selected) && !empty($message) && !empty($checkbox)) { // If passed, check email address if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) { //If failed, Email address is not valid $msg = 'Please use a valid email address'; $msgClass = 'alert-danger'; } else { //Recipient email address and information to be sent to them $toEmail = 'hello@example.co.uk'; $subject = 'Contact Request from Website'; $body = '<h2>Contact Request</h2> <h4>Name</h4><p>'.$firstname. ''.$lastname.'</p> <h4>Phone Number</h4><p>'.$phonenumber.'</p> <h4>Email Address</h4><p>'.$email.'</p> <h4>Subject</h4><p>'.$selected.'</p> '; // Email Headers $headers = "MIME-VERSION: 1.0" ."\r\n"; $headers .="Content-Type:text/html;charset=UTF-8" ."\r\n"; // Additional Headers $headers .= "From: " .$firstname. " ".$lastname." <".$email.">" ."\r\n"; if(mail($toEmail, $subject, $body, $headers)) { // Message Sent $msg = 'Your message has been sent'; $msgClass = 'alert-success'; } else { // Message failed $msg = 'Your message has NOT been sent'; $msgClass = 'alert-danger'; } } } else { //Failed $msg = 'Please fill in all fields'; $msgClass = 'alert-danger'; } } ?> <div class="container clearfix content-container"> <h1 class="section-title">Contact Us</h1> <p>If you have any questions about the services we provide or would like to chat about a new website project, please get in touch using any of the options below. We would love to hear from you!</p> <!--Contact Page Row--> <div class="row"> <div class="col-lg-6 contact-details"> <div class="row"> <div class="col-lg-12"> <img src="assets/img/contact-us.jpg" class="img-responsive d-block contact-image" alt="Contact Us Image"> </div> </div> <div class="row"> <div class="col-lg-12 contact-name"> <span class="d-inline-block contact-inline-block"><i class="fas fa-user fa-2x"> </i></span> <span class="d-inline-block"><p class="contact-details">sn0wman23</p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-phone"> <span class="d-inline-block contact-inline-block"><a href="tel:+447740484798"><i class="fas fa-mobile-alt fa-2x"></i></a></span> <span class="d-inline-block"><a href="tel:+441234567890"><p class="contact-details">01234 567890</a></p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-email"> <span class="d-inline-block contact-inline-block"><a href="mailto:hello@example.co.uk"><i class="fas fa-envelope-square fa-2x"></i></a></span> <span class="d-inline-block"><a href="mailto:hello@example.co.uk"><p class="contact-details">hello@example.co.uk</a></p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-fb"> <span class="d-inline-block contact-inline-block"><a href="https://www.facebook.com/" target="_blank"><i class="fab fa-facebook-square fa-2x"></a></i></span> <span class="d-inline-block"><a href="https://www.facebook.com/example/" target="_blank"><p class="contact-details">@example</a></p></span> </div> </div> </div> <!--Contact Form--> <div class="col-lg-6 contact-form d-block"> <?php if($msg != ''): ?> <div class="alert <?php echo $msgClass; ?>"><?php echo $msg; ?></div> <?php endif;?> <form method="post" action="contact.php" role="form"> <div class=" row form-group"> <div class="col-lg-6"> <label for="firstnameid">First name:</label> <input type="text" name="firstname" class="form-control mb-3" id="firstnameid"> </div> <div class="col-lg-6"> <label for="lastnameid">Last name:</label> <input type="text" name="lastname" class="form-control mb-3" id="lastnameid"> </div> </div> <div class="row form-group"> <div class="col-lg-6"> <label for="phonenumber">Phone number:</label> <input type="tel" name="phonenumber" class="form-control mb-3" id="phonenumberid"> </div> <div class="col-lg-6"> <label for="emailid">Email address:</label> <input type="email" name="email" class="form-control mb-3" id="emailid"> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <label for="subjectid">How can I help?:</label> <select class="form-control mb-3" id="subjectid"> <option selected>Select one from this list</option> <option value="1">Value 1</option> <option value="2">Value 2</option> <option value="3">Value 3</option> </select> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <label for="messageid">Tell me a little bit mo </label> <textarea name="message" class="form-control mb-3" id="messageid" rows="6"></textarea> </div> </div> <div class="row form-group"> <div class="col-lg-12 form-check"> <input type="checkbox" name="checkbox" class="form-check-input" id="formcheckid"> <label for="formcheckid" class=form-check-label mb-3>By checking this tickbox you have confirmed that we can collect the information in this form for the purposes outlined in our <a href="privacy-policy.html">privacy policy.</a></label> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <button type="submit" name="submit" class="btn btn-primary mt-4">Send Message </button> </div> </div> </form> </div> <!--Contact Form End--> </div> <!--Contact Page Row End--> </div> <!--Container end--> <?php echo file_get_contents('footer.php'); ?>
I want in my form to validate on the fly(when the user enters the user name) to validate if the user name exists or not. How am i supposed to check if the field name is the same or not with a name in the database.Should i use ajax or javascript? is there any simple example on how to do that. |