PHP - Displaying Form Errors But Avoid Clearing Already-filled Data
I've got a basic form setup on my site that requires the user to fill out the required fields. When one of the fields isn't filled out, the error message for that specific input area is displayed, etc. However, all the information from the form that the user filled out is removed..
I want the user to be able to fill out the form, hit submit, and if any errors, show the specific error but also keep the input boxes populated with the data the user filled out so he/she does not have to re type everything. if(!empty($_POST['submitFeature'])) { // set variables $featurename = mysql_real_escape_string($_POST['featurename']); $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']); $src = $_FILES['featureupload']['tmp_name']; $featuresize = $_FILES['featureupload']['size']; $limitsize = 3000000; if(!empty($featurename) && !empty($name) && !empty($email) && !empty($email2) && !empty($city) && !empty($state) && ($email == $email2) && !empty($_FILES['featureupload']['tmp_name']) && ($featuresize < $limitsize)) { // IF ALL IS CORRECT, SUBMIT INFO } else { print ' <ul class="errorlist"> <li class="alert">Please fill out the required fields.</li> '; if (empty($name)) { echo ' <li>* Full Name</li>' . "\n"; $errorname = 'TRUE'; } if (empty($email)) { echo ' <li>* Email</li>' . "\n"; $erroremail = 'TRUE'; } print ' </ul> '; } // 1 - B. END REQUIRED FIELDS ERROR CODES } ?> <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> <div style="float: left;"> <span class="copy-answer">Your Information</span> <div class="formSec"><label for="name" class="required">Full Name: <?php if(isset($errorname)){echo '<span class="error">*<span>';}?></label> <input type="text" name="name" id="name" value="" maxlength="25" /></div> <div class="formSec"><label for="email" class="required">Email: <?php if(isset($erroremail)){echo '<span class="error">*<span>';}?></label> <input type="text" name="email" id="email" value="" /></div> <input class="submit" type="submit" name="submitFeature" value="Submit Your Feature" /> </form> Similar TutorialsI am adding line items in my invoice script, while adding i validate the data. if validation fails, it will display error message with entered data filled in the form. If it clears the validation, data gets submitted to database and displays the same . Here i can add many line items, so this process should keep repeating. Everything is working fine. But when the form submits it should display error in one place and display the submitted data in other place. Here is my form
<form action="" method="post"> <div class="form-row"> <div class="col-md-4 mb-30"> <label for="validationDefault01">Select Customer</label> <select name="customer" class="form-control" id="validationDefault01" required> <option value=""></option> <?php $c1 = mysqli_query($con, "SELECT * FROM customers WHERE status='Active'") or die (mysqli_error($con)); while($c2 = mysqli_fetch_array($c1)) { ?> <option value="<?php echo $c2["cid"]; ?>" <?php if($c2["cid"] == $_POST['customer'] ) { echo "selected"; } ?> ><?php echo $c2["name"]; ?></option> <?php } ?> </select> </div> <div class="col-md-4 mb-30"> <label for="validationDefault02">Date</label> <input type="text" class="form-control" name="edate" id="datepicker" value="<?php echo isset($_POST["edate"]) ? $_POST["edate"] : $today; ?>" required /> </div> </div> <!-- line item --> <div class="table-responsive"> <table class="table table-active table-bordered table-sm"> <thead class="thead-active"> <tr> <th>Name</th> <th>Description</th> <th>UOM</th> <th>Price</th> <th>Stock</th> <th>Qty</th> </tr> </thead> <tr> <td><input type="text" id="productname" name="productname" value="<?php echo isset($_POST["productname"]) ? $_POST["productname"] : ''; ?>" required ></td> <input type="hidden" id="productcode" name="productcode" value="<?php echo isset($_POST["productcode"]) ? $_POST["productcode"] : ''; ?>" /> <td><textarea id="description" name="description"><?php echo isset($_POST["description"]) ? $_POST["description"] : ''; ?></textarea></td> <td><select name="uom" id="uom"> <?php $su1 = mysqli_query($con, "select * from uom"); while($su2 = mysqli_fetch_array($su1)) { ?> <option value="<?php echo $su2["uom_name"]; ?>" <?php if($su2["uom_name"] == $_POST['uom'] ) { echo "selected"; } ?> ><?php echo $su2["uom_name"]; ?></option> <?php } ?> </select> </td> <td><input type="text" required id="price" name="price" value="<?php echo isset($_POST["price"]) ? $_POST["price"] : ''; ?>" /></td> <td><input type="text" readonly id="stock" name="stock" value="<?php echo isset($_POST["stock"]) ? $_POST["stock"] : ''; ?>" /></td> <td><input type="text" required id="quantity" name="quantity" value="<?php echo isset($_POST["quantity"]) ? $_POST["quantity"] : ''; ?>" /></td> </tr> </table> <!-- line item ends---> <div class="form-row"> <div class="col-md-4 mb-30"> <input name="add" class="btn btn-success" type="submit" value="Add" /> </div> </div> </form> form submission <?php if(isset($_POST['add'])) { $customer = $_POST['customer']; $edate1 = $_POST['edate']; $edate = date('Y-m-d', strtotime((str_replace('/','-',$edate1)))); $pname = $_POST['productname']; $pcode = $_POST['productcode']; $uom = $_POST['uom']; $price = $_POST['price']; $quantity = $_POST['quantity']; $pc = mysqli_query($con, "SELECT min_price FROM items WHERE item_id=".$pcode."") or die (mysqli_error($con)); $prow = mysqli_fetch_array($pc); // This error part should be displayed inside <div id="error"></div> which is above the form if($price<$prow['min_price']) { echo '<div class="alert alert-inv alert-inv-danger alert-wth-icon alert-dismissible fade show" role="alert"> <span class="alert-icon-wrap"><i class="zmdi zmdi-bug"></i></span> Price should not be lesser than minimum price defined. <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div>'; } else { //data gets inserted into invoice table and displays submited data in table format // this part should be displayed below the form inside <div id="success"></div> } }
When I submitted my Form & refresh then browser resend all data again into database, So anybody know any solution of this to avoid data resend after refreshing browser.. 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> This could be PHP or MySql so putting it in PHP forum for now... I have code below (last code listed) which processes a dynamically created Form which could have anywhere from 0 to 6 fields. So I clean all fields whether they were posted or not and then I update the mySQL table. The problem with this code below is that if, say, $cextra was not posted (i.e. it wasnt on the dynamically created form), then this code would enter a blank into the table for $cextra (i.e. if there was already a value in the table for $cextra, it gets overwritten, which is bad). What is the best way to handle this? I'm thinking i have to break my SQL query into a bunch of if/else statements like this... Code: [Select] $sql = "UPDATE cluesanswers SET "; if (isset($_POST['ctext'])){ echo "ctext='$ctext',"; } else { //do nothing } and so on 5 more times.... That seems horribly hackish/inefficient. Is there a better way? Code: [Select] if (isset($_POST['hidden']) && $_POST['hidden'] == "edit") { $cimage=trim(mysql_prep($_POST['cimage'])); $ctext=trim(mysql_prep($_POST['ctext'])); $cextra=trim(mysql_prep($_POST['cextra'])); $atext=trim(mysql_prep($_POST['atext'])); $aextra=trim(mysql_prep($_POST['aextra'])); $aimage=trim(mysql_prep($_POST['aimage'])); //update the answer edits $sql = "UPDATE cluesanswers SET ctext='$ctext', cextra='$cextra', cimage='$cimage', atext='$atext', aextra='$aextra', aimage='$aimage'"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { } Hi i'm new to PHP/web development but not new to coding. I have some php code that I grabed from a template where I am selecting data from a file and having it diplay on the screen in a form. My $query = "select * from file where" statement works and bring the data back to the screen. However, I want the data to be returned in a textarea instead of a text field that is not big enough to display the 3 paragraph that i need to display. Please see code below, thsi code will return the data but the text box only returns the data in a line, I need the data to be returned in a textarea, so I can update it. I have looked for the correct syntex with no luck, please correct me. $row = mysql_fetch_array($result, MYSQL_ASSOC); $recordid = $row['recordid']; $homepage = $row['homepage']; echo "<h2>Update About Us Information</h2>\n"; echo "<form enctype=\"multipart/form-data\" action=\"admin.php\" method=\"post\">\n"; echo "<table width=\"100%\" cellpadding=\"1\" border=\"1\">\n"; echo "<tr><td><h3>Record ID</h3></td><td>$recordid</td></tr>\n"; echo "<tr><td><h3>Homepage</h3></td><td><input type=\"text\" size=\"100\" name=\"homepage\" value=\"$homepage\" /></td></tr>\n"; echo "</table>\n"; echo "<input type=\"submit\" name=\"button\" value=\"Update\">\n"; echo "<input type=\"submit\" name=\"button\" value=\"Delete Product\">\n"; echo "</form>\n"; 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 displaying mysql data in a table form using php. The first attached pic shows how is it looking with the current code. As you can see there are heading on the left and top of the table. So user can make booking on a specific day (heading is on the top for days) and for specific duration of time(headings are on the left). As in first pic, there has been a booking on Wed at 10 o clock, but the problem is, it is displaying duration just for half an hour. As this duration is from 10 o clock to 11 o clock. So what I want to do is in the second pic. Please view the second pic. In the second pic I want to display the highlighted area in blie because all this time is booked or reserved. Here is my current code. Code: [Select] <?php require("dbconnect/dbconnect.php"); $building = $_POST['building']; $block = $_POST['block']; $d_m = $_POST['d_m']; $choose_one = $_POST['choose_one']; function get_data($table, $choose_one) { $bool = 1; $get_days = mysql_query("SELECT * FROM days"); $get_times = mysql_query("SELECT * FROM time"); $days = mysql_num_rows($get_days); //$row_day_id = mysql_fetch_assoc($get_days); //$day_id_db = $row['dayid']; echo "<table cellspacing='0' border='0' cellpadding='5'> <tr> <th scope='col' width='100'></th>"; while($row_time = mysql_fetch_assoc($get_times)) { while($bool <= $days) { $row_days = mysql_fetch_assoc($get_days); $dayname = $row_days['days']; echo " <th scope='col' width='100'>$dayname</th> "; $bool++; } $day_id = 1; $timeid = $row_time['timeid']; $time = $row_time['time']; echo " <tr> <th scope='row' width='100' height='50'>$time</th>"; while($day_id <= $days) { $get = mysql_query(" SELECT * FROM $table WHERE dayid='$day_id' AND timeid_from='$timeid' AND d_m='$choose_one' ") or die(mysql_error()); if(mysql_numrows($get) > 0) { $row = mysql_fetch_assoc($get); $block = $row['block']; $apt = $row['apartment_no']; $room = $row['room_no']; $d_m = $row['d_m']; $timeid_to = $row['timeid_to']; echo " <td width='110' height='50' bgcolor='lightblue'> <b>Block:</b> $block<br /> <b>Apartment:</b> $apt<br /> <b>Room:</b> $room </td> "; //echo "</tr>"; } else { echo " <td width='110' height='50' bgcolor='green'></td> "; } $day_id++; } //end of second inner while loop echo "</tr>"; } //end of outer while loop echo "</table>"; } if($building) { if($block) { if($d_m) { if($choose_one) { if($building == 'mik') { if($block == 'Block A' || $block == 'Block B') { get_data('reserve_mik_ab', $choose_one); } else if ($block == 'Block C' || $block == 'Block D') { get_data('reserve_mik_cd', $choose_one); } } if($building == 'p') { get_data('reserve_p',$choose_one); } } else { echo "Choose one!"; } } } } ?> Please help! Hello there, I have a problem with a form, as soon as I fill the for using a query. The buttons doesn't work anymore. They work when i open the page, they have somoe js to emable and diable controls. but when i do a search and get the form filled, non of the controls work anymore. Any advise? Hello Everyone, I m making an attendance application. I have an issue with following code, Code: [Select] <?php session_start(); require_once("conf.php"); mysql_select_db('site'); $subjects=$_GET['sublen']; $username=$_SESSION['user']; for($i=1;$i<=$subjects;$i++) { $subject=$_GET[',Sub'.$i]; $query="INSERT INTO Subjects(id,Subjects,User,Classs) VALUES($i,'$subject','$username','F.Y.B.Sc')"; $true=mysql_query($query) or die("Cannot Store subjects".mysql_error()); } ?> <html> <head> <link href="../css/style.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="../js/jquery.js"></script> </head> <body> <div id="main"> <div id="logo"> KiMi... </div> <div id="header"> <ul> <li><a href="index.html">Home</a></li> <li><a href="php/subjectsTable.php">Create Subjects</a></li> <li><a href="html/form.html">Contact Us</a></li> <li><a href="html/register.php">Register!</a></li> </ul> </div> <div id="nav"> </div> <div id="content"> <?php if($true) { echo "<div id='dynamicDiv'>"; echo "<div> Subjects stored Successfully!</div></br></br>"; $query="SELECT * FROM Subjects Where User='$username'"; $result=mysql_query($query) or die("Cannot Fetch Data"); echo "<table id='table'>"; echo "<tr><td> </td><td>Subjects</td><td>Class</td></tr>"; while($row=mysql_fetch_array($result)) { echo "<tr><td><input type='checkbox' name='box[]'/> </td>"; echo "<td>"; echo $row['Subjects']; echo "</td>"; echo "<td>"; echo $row['Classs']; echo "</td>"; echo "</tr>"; } echo "</table>"; echo "</div>"; } ?> </div> <div id="footer"> © Copyright Amit K. Goda 2011-2012 </div> </div> </body> </html> In the above code i m storing data into database which has been passed into $_GET array. The Code is this Quote <?php session_start(); require_once("conf.php"); mysql_select_db('site'); $subjects=$_GET['sublen']; $username=$_SESSION['user']; for($i=1;$i<=$subjects;$i++) { $subject=$_GET[',Sub'.$i]; $query="INSERT INTO Subjects(id,Subjects,User,Classs) VALUES($i,'$subject','$username','F.Y.B.Sc')"; $true=mysql_query($query) or die("Cannot Store subjects".mysql_error()); } ?> the data is stored but the issue is, since i have data coming in $_GET array when i reload my page the same data is stored again inmy database. So any suggesstions how can i avoid that??? Any Help will be highly appreciated I have a query that gets staff on a particular day then performs a while loop selecting each member that works on that day and the times they work between. I have a for loop in that while loop that lists apointment times for each staff member every 15mins between the times they work, this works fine. I then have in the for loop a while loop that checks for existing appontments in the appointment table and changes the appointment slot for times that are booked to booked. I have found though that the second while loops causes doubling of results when an appointment is found, so I need to work out how to restructure this code so that i dont get the doubling effect of result. you can see the result of the script here http://justrelax.net.au/datetest.php and the code that causes the problem is // convert to US format $input="$month/$day/$year"; // readable date $readDATE="$day/$month/$year"; // convert for mysql date $sqlDATE="$year-$month-$day"; // get day of the week $weekday=date(l, strtotime($input)); echo $weekday."<br/>"; // get working staff from staff table $staffSQL=mysql_query("SELECT * FROM staff WHERE ".$weekday." != 'off' AND onLEAVE='no' AND ACTIVE='yes' ORDER BY staffID ASC"); // return results putenv("TZ=Australia/Adelaide"); while ($staff=mysql_fetch_array($staffSQL)) { $name=$staff['staffNAME']; $avail=$staff[$weekday]; $staffID=$staff['staffID']; list($first, $last)=explode(" ", $name); list($in, $out)=explode("-", $avail); $firstTIME="$sqlDATE $in:00"; $lastTIME="$sqlDATE $out:00"; echo "$first is available between $avail on $weekday<br/>"; $in2=strtotime($firstTIME); $out2=strtotime($lastTIME); $stop=$out2-900; echo $in2." - time start - $firstTIME<br/>"; echo $out2." - time finish - $lastTIME<br/>"; for ($inc=$in2;$inc<=$stop;$inc+=900) { $existSQL=mysql_query("SELECT * FROM appointment WHERE date='$sqlDATE' AND staffID='$staffID'"); if (mysql_num_rows($existSQL)>=1) { while ($appointV=mysql_fetch_array($existSQL)) { $resSTART=$appointV['dateTIME']; $length=$appointV['totalTIME']; $resEND=$resSTART+($length*60); if ($inc>=$resSTART && $inc<=$resEND) { echo "Appointment time is ".date("g.i a", $inc)." <font color='red'><< $first BOOKED</font><br/>"; } else if ($inc<$resSTART || $inc>$resEND) { echo "Appointment time is ".date("g.i a", $inc)." <font color='green'><< $first AVAILABLE</font><br/>"; } } } if (mysql_num_rows($existSQL)==0) { echo "Appointment time is ".date("g.i a", $inc)." <font color='green'><< $first AVAILABLE</font><br/>"; } } } could really use some help on this I have been trying different things for a few days now. Hello all! Very frustrated PHP newbie here. I am trying to simply get my code to display errors. I have gone into the php.ini file, changed error_reporting to E_ALL, changed display_errors to On, changed display_startup_errors to On, and even added the line ini_set('display_errors', 'on'); to my code. I restarted the server after every change, and still I see no errors. My boss wants me to reach out to the community for answers rather than handing them to me himself. So here I am. Please advise! Thank you very much in advance. The Script:
<h1>Do Add a Message to the MySQL Database</h1> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> <textarea name="message"></textarea> <br/> <input type="submit" name="submit"/> </form> <?php // The Connection to the Database // Taken Out ?> <?php // To insert the text data into the MySQL database. if(isset($_POST['submit'])){ $tqs = "INSERT INTO messages (`message`) VALUES ('{$_POST['message']}')"; $tqr = mysqli_query($dbc, $tqs) or die(mysqli_error($dbc)); } ?> <?php // To select the text data from the MySQL database. $tqs = "SELECT * FROM messages"; $tqr = mysqli_query($dbc, $tqs); // To print out the text data inside of table on the page. echo "<h1>This Is Where the Messages Gets Printed on Screen</h1>"; echo "<table><tr><td>ID</td><td>The Message</td></tr>"; while($row = mysqli_fetch_assoc($tqr)){ echo "<tr><td>" . $row['id'] . "</td><td>" . $row['message'] . "</td></tr>"; } echo "</table>"; ?>1. When I have added text with the form to the MySQL database... 2. ... and I have clicked on "page reload" in Firefox to reload the page... 3. ... then the before submitted text gets submitted again to the MySQL database. So basically, add text with the form to the MySQL database, reload the page in Firefox, and the before added text will get submitted to the MySQL database again. My Question Is: What is the proper way to avoid this? Edited by glassfish, 06 October 2014 - 10:18 AM. I have a Credit Card Payment Form. A few things... 1.) For non-financial fields, I'm using a "sticky form". Code: [Select] <label for="firstName">First Name:</label> <input id="firstName" name="firstName" class="text" type="text" maxlength="20" value="<?php echo $firstName; ?>" /> After the user successfully submits the form, how can I erase these values out? Right now, if you hit the "Back" button, the form data is still there, which isn't very secure?! 2.) I read somewhere, that HTML secretly cache form values, and there is something you add to your HTML to prevent these - especially on the Credit Card # field. Any idea what I'm talking about? BTW, I'm not using Cookies, Sessions, or a DB to store any form data. Thanks, Debbie Hi, I'm quite a newbie to PHP and am doing a website. Have got a login working and the registration half way there, but am now in process of putting validation in Registration form. Have got the errors appearing if domething isn't filled in or if the username is taken however, it clears all the fields and i would like it to keep the values in them if possible. Is there an easy way round this? I can give my code if needed Cozzy Code: [Select] $genre = $_POST['listMovies']; $result = mysql_query("SELECT * FROM movieTable SORT BY title"); $column = 1; define("COLUMNS", 2); $movieCounter = 0; echo "<h1>by " .$genre ."</h1><table>"; while ($info = mysql_fetch_array($result)) { $genre1 = $info['genre1']; $genre2 = $info['genre2']; $genre3 = $info['genre3']; $title = $info['title']; $link = $info['imdbLink']; if ($genre == $genre1 || $genre == $genre2 || $genre == $genre3) { $movieCounter++; if ($column == 1) {echo "<tr>";} echo "<td><a href='" .$link ."'>".$title ."</a></td>"; $column++; if ($column > COLUMNS) { echo "</tr>"; $column = 1; } } } echo "<table><tr><td>" .$movieCounter ." movies found.</td></tr></table>"; if ($column > 1 && $column <= COLUMNS) { while ($column++ <= COLUMNS) echo "<td></td>"; echo "</tr>"; } echo "</table>"; $genre = ""; now that you have the code, i have 2 questions about this. first one is this. whenever i first load this code everything is empty as it should be. then i select from a form a movie genre and everything work lovely. the problem is that the movies that are loaded are still there when i come back to the page. i need a way to clearing this out everytime the code is run, while still displaying the movies. also .. this is just a php noob question here. why is that when i run a query like this Code: [Select] $result = mysql_query("SELECT * FROM movieTable SORT BY title"); i cannot use mysql_fetch_array or mysql_fetch_row? but it works when i do it like this Code: [Select] $result = mysql_query("SELECT * FROM movieTable"); like i said that's just a noob question that i cannot for the life of me figure out. thanks for the help, this forum has been the biggest help to me learning php. I have a form where people will be putting in specific info such as their names and other info. When the form is posted I need to add a "." between the fields on the output depending on if it is filled out or not if field is blank do not need a "." Example if they put in their name Bob Marley on the form I need it to appear on the output as Bob.Marley. Here is the code using currently which also excludes blank fields echo $_POST["First"]; if(isset($_POST["Middle"])){ echo $_POST["Middle"]; } echo $_POST["Last"]; Hello all, I'm writing a page with a simple database with a table called recipes in it with a series of recipes (go figure). I want to display a list of the recipe titles in ascending alphabetical order with each title linked to another page that displays all of the information about the recipe. I can't seem to get anything to display though (not even the titles) but I'm not getting any errors returned either. It seems as if there is nothing in the table to display (even though there are 40 records there). Any help would be greatly appreciated. Here is the code I have so far: Code: [Select] <?php $dbhost = 'localhost'; $dbuser = '*****'; $dbpass = '*****'; $dbname = '*******'; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to database'); mysql_select_db($dbname) or die('Error selecting the database'); // select data from db to use $result = mysql_query("SELECT * FROM recipes ORDER BY title ASC LIMIT 0,50") or die('mysql_error()'.'Error: ' .mysql_errno() ); //display the data while($row = mysql_fetch_array($result)); { echo"<b><center>Healthy Lifestyle Gourmet Recipes</center></b><br /><br />"; echo "<span class=\"recipelink\"><a href=\"reciperesults.php?id=".$row['id']."\" target=\"_blank\">".$row['title']."</a></span><br/>\n"; } mysql_close(); ?> I starred out the connection variables but, they are all correct in my code (I'm not getting the "or die" errors) SET UP: Windows vista # XAMPP 1.7.3, # Apache 2.2.14 (IPv6 enabled) + OpenSSL 0.9.8l # MySQL 5.1.41 + PBXT engine # PHP 5.3.1 # phpMyAdmin Error message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') VALUES ('qwerty','uiop','asd')' at line 2 I'm trying to get this multi page order form to insert information into two tables via a session. But it comes up with the above error message. This script worked perfectly with one table but as soon as I coded he information to go into two tables it screwed up. Is it the sprint <?php //let's start our session, so we have access to stored data session_start(); session_register('membership_type'); session_register('terms_and_conditions'); include 'db.inc.php'; $db = mysql_connect('localhost', 'root', '') or die ('Unable to connect. Check your connection parameters.'); mysql_select_db('ourgallery', $db) or die(mysql_error($db)); //let's create the query $query = sprintf("INSERT INTO subscriptions ( name, email_address, membership_type,) VALUES ('%s','%s','%s')", mysql_real_escape_string($_SESSION['name']), mysql_real_escape_string($_SESSION['email_address']), mysql_real_escape_string($_SESSION['membership_type'])); //let's run the query $result = mysql_query($query, $db) or die(mysql_error($db)); $query = sprintf("INSERT INTO site_user_info ( terms_and_conditions, name_on_card, credit_card_number, credit_card_expiration_data) VALUES ('%s','%s','%s','%s')", mysql_real_escape_string($_SESSION['terms_and_conditions']), mysql_real_escape_string($_POST['name_on_card']), mysql_real_escape_string($_POST['credit_card_number']), mysql_real_escape_string($_POST['credit_card_expiration_data'])); //let's run the query $result = mysql_query($query, $db) or die(mysql_error($db)); echo '$result'; ?> I'm trying to insert into this database: <?php require 'db.inc.php'; $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Unable to connect. Check your connection parameters.'); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); $query = 'CREATE TABLE IF NOT EXISTS subscriptions ( name VARCHAR(50) NOT NULL, email_address VARCHAR(50), membership_type VARCHAR(50), PRIMARY KEY (name) ) ENGINE=MyISAM'; mysql_query($query, $db) or die (mysql_error($db)); // create the user information table $query = 'CREATE TABLE IF NOT EXISTS site_user_info ( name VARCHAR(50) NOT NULL, terms_and_conditions VARCHAR(50) NOT NULL, name_on_card VARCHAR(50), credit_card_number VARCHAR(50), credit_card_expiration_data VARCHAR(50), FOREIGN KEY (name) REFERENCES subscriptions(name) ) ENGINE=MyISAM'; mysql_query($query, $db) or die (mysql_error($db)); echo 'Success!'; ?> What am I doing wrong? is there a code spell checker ? Also should I use the mysql_real_escape_string() on the user input as they become sessions variables or is it okay to wait and clean the input as it gets inserted in the table? Thanks for your help. I have a form on our website that a user can fill out for custom product. I want the form data to be 1) stored into a mysql database AND after storing said data, 2) email the same data to our sales department. 1) The form data DOES get stored into mysql database (except for the first two fields, for some weird reason) 2) I added a "mail" section to the php file that stores the data into the database, but it is not working correctly. I have stripped the email portion down to sending just one of the fields in the "message" to make it easier for troubleshooting I have included here, both the form section of the html file, and the formdata.php file that processes the data for your analysis. I am relatively new to php so there are going to be some issues with security, but I can work on those after I get the store & email process to work correctly. Please review my code and see if anyone can be of assistance. I looked through the forums and couldn't find another issue that was the same as mine. If I just overlooked, please tell me the thread post #. Thanks THE FORM WHICH COLLECTS THE DATA ******************************* <form method=POST action=formdata.php> <table width="640" border=0 align="center"> <tr> <td align=right><b>First Name</b></td> <td><input type=text name=FName size=25></td> <td><div align="right"><b>Telephone</b></div></td> <td><input type=text name=Tel size=25></td> </tr> <tr> <td align=right><b>Last Name</b></td> <td><input type=text name=LName size=25></td> <td><div align="right"><b>Fax</b></div></td> <td><input type=text name=Fax size=25></td> </tr> <tr> <td align=right><b>Title</b></td> <td><input type=text name=Title size=25></td> <td><div align="right"><b>Email</b></div></td> <td><input type=text name=Email size=50></td> </tr> <tr> <td align=right><b>Company</b></td> <td><input type=text name=Comp size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Address</b></td> <td><input type=text name=Addr size=25></td> <td><div align="right"><b>Estimated Annual Volume</b></div></td> <td><input type=text name=EAV size=25></td> </tr> <tr> <td align=right><b>City</b></td> <td><input type=text name=City size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>State/Province</b></td> <td><input type=text name=SProv size=25></td> <td><div align="right"><b>Application</b></div></td> <td><input type=text name=Appl size=25></td> </tr> <tr> <td align=right><b>Country</b></td> <td><input type=text name=Ctry size=25></td> <td><div align="right"><b>Type of System</b></div></td> <td><input type=text name=Syst size=25></td> </tr> <tr> <td align=right><b>Zip/Postal Code</b></td> <td><input type=text name=ZPC size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td><div align="right"><strong><font color="#FFFF00" face="Arial, Helvetica, sans-serif">COIL DESIGN</font></strong></div></td> <td><font color="#FFFF00" face="Arial, Helvetica, sans-serif"><strong>PARAMETERS</strong></font></td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Primary Resistance (ohms)</b></td> <td><input type=text name=Pres size=25></td> <td><div align="right"><b>Primary Inductance (mH)</b></div></td> <td><input type=text name=Pind size=25></td> </tr> <tr> <td align=right><b>Secondary Resistance (ohms)</b></td> <td><input type=text name=Sres size=25></td> <td><div align="right"><b>Secondary Inductance (H)</b></div></td> <td><input type=text name=Sind size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Peak Operating Current (Amps)</b></td> <td><input type=text name=POC size=25></td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b>Output Energy (mJ)</b></td> <td><input type=text name=Egy size=25></td> <td><div align="right"><b>Output Voltage (kV)</b></div></td> <td><input type=text name=Volt size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right><b># HV Towers per Coil</b></td> <td><input type=text name=TPC size=25></td> <td><div align="right"><b># of Coils per Package</b></div></td> <td><input type=text name=CPP size=25></td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td align=right> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <th colspan=4><b>Please enter any additional information he </b></th> </tr> <tr> <th colspan=4><textarea name=Mess cols=50 rows=10 id="Message"></textarea></th> </tr> </table> </dl> <div align="center"> <p> <input type=hidden name=BodyTag value="<body bgcolor="#484589" text="#FFFFFF" link="#FFFF00" alink="#FFFFFF" vlink="#FF7F00">"> <input type=hidden name=FA value=SendMail> </p> <p><font color="#FFFF00" face="Arial, Helvetica, sans-serif"><strong>PLEASE MAKE SURE ALL INFORMATION<br> IS CORRECT BEFORE SUBMITTING</strong></font></p> <p> <input type=submit value="Submit Form"> </p> </div> </form> THE FILE THAT PROCESSES THE FORM DATA (formdata.php) *********************************************** <?php $con = mysql_connect("localhost","XXX","XXX"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("customform", $con); $sql="INSERT INTO formdata (Fname, Lname, Title, Comp, Addr, City, SProv, Ctry, ZPC, Tel, Fax, Email, EAV, Appl, Syst, Pres, Pind, Sres, Sind, POC, Egy, Volt, TPC, CPP, Mess) VALUES ('$_POST[Fname]','$_POST[Lname]','$_POST[Title]','$_POST[Comp]','$_POST[Addr]','$_POST[City]','$_POST[SProv]','$_POST[Ctry]','$_POST[ZPC]','$_POST[Tel]','$_POST[Fax]','$_POST[Email]','$_POST[EAV]','$_POST[Appl]','$_POST[Syst]','$_POST[Pres]','$_POST[Pind]','$_POST[Sres]','$_POST[Sind]','$_POST[POC]','$_POST[Egy]','$_POST[Volt]','$_POST[TPC]','$_POST[CPP]','$_POST[Mess]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "Your Information Was Successfully Posted"; mysql_close($con); $to = "recipient email address here"; $subject = "Custom Form"; $email = $_POST['Email'] ; $message = $_POST['Comp'] ; $headers = "From: $Email"; $sent = mail($to, $subject, $message, $headers) ; if($sent) {print "Your mail was sent successfully"; } else {print "We encountered an error sending your mail"; } ?> Hello im working on a project which involves marking attendance via an RFID tag and saving the time into an sql file. Everything seems to be working fine and the time stamp is successfully punched into the SQL but something is wrong with the php code thats supposed to display this data. Please if any one can take a look and help.
MY CODE for displaying the data (ViewAttendance.php): <?php include_once("header.php"); $attData = array(); $totDays = 0; if(isset($_REQUEST['submit'])){ $totDays = cal_days_in_month(CAL_GREGORIAN,$_REQUEST['month'],$_REQUEST['year']); $attData = $commonObj->getAttendanceData($_REQUEST['month'],$_REQUEST['year']); //print_r($attData); //print_r(date("d",strtotime($attData[0]['punch_time']))); } ?> <div class="container"> <div class="row"> <div class="col-sm-12"> <h4>Showing Attendance</h4> <form name="showAtt" method="post"> <div class="col-sm-4"><label>Select Month</label> <select name="month" class="form-control"> <?php for($i=1;$i<=12;$i++){?> <option value="<?php echo $i;?>"><?php echo $i;?></option> <?php }?> </select> </div> <div class="col-sm-4"><label>Select Year</label> <select name="year" class="form-control"> <?php for($i=date("Y");$i>=2010;$i--){?> <option value="<?php echo $i;?>"><?php echo $i;?></option> <?php }?> </select> </div> <div class="col-sm-4"> <p> </p> <input type="submit" value="Show" name="submit" class="btn btn-primary"> </div> </form> </div> </div> <div class="row"> <div class="col-sm-2"> <label class="btn btn-success btn-sm">Month:<?php echo @$_REQUEST['month'];?></label> </div> <div class="col-sm-2"><label class="btn btn-info btn-sm">Year: <?php echo @$_REQUEST['year'];?></label></div> </div> <div class="row"> <div class="col-sm-12" style="overflow: scroll;"> <?php if($totDays>0){?> <table class="table table-striped"> <tr> <th> Employee Name </th> <?php for($i=1;$i<=$totDays;$i++){?> <th> <?php echo $i;?> </th> <?php }?> <?php foreach($attData as $attk=>$attv){ $punchin = $commonObj->getTimeOfDate($attData[$attk]['punchin']); $punchout = $commonObj->getTimeOfDate($attData[$attk]['punchout']); ?> <tr> <th class="danger"> <?php echo $attv['name'];?> </th> <?php for($i=1;$i<=$totDays;$i++){?> <?php if($commonObj->getDayOfDate($attData[$attk]['punch_time']) == $i){ echo "<td class='success' id='att_$i'>".$punchin.'-'.$punchout;?> <table class="table table-responsive"style="display: none; position:relative;min-width:100px;max-width:200px; margin-top: -40px;" id="<?php echo "det_att_".$i;?>"> <tr> <td>Total hours:</td> <td><?php echo $commonObj->getHoursBetweenDates($attData[$attk]['punchin'],$attData[$attk]['punchout']);?> </td></tr> <tr> <td>UID:</td> <td><?php echo $attData[$attk]['rfid_uid'];?></td> </tr> </table> <?php }else {echo "<td class='info'>#na";}?> </td> <?php }?> </tr> <?php }?> </tr> </table> <?php }?> </div> </div> </div> </body> </html> <script> $(document).ready(function(){ $("td").hover( function () { var id = "#det_"+this.id; $(id).css({"display":"block"}); }, function () { var id = "#det_"+this.id; $(id).css({"display":"none"}); //console.log(id); //$(id).css("display","block"); }); }); </script> Display of (ViewAttendance.php):
MY SQL TABLE :
|