PHP - Please Help With Form For Adding Data To Db
Hi People.
I am having a problem with this form and for the life of me can't see where I have made the mistake. On line 33 I have commented where I get the problem. If I remove this line (or comment it out) and remove the insert statements for that line then it all works and I can see the php form on my live site. However, with this in, as it is, I can't see anything, I get a blank page altogether. Please, can anyone see my mistake? I have been going over the code now for ages and it's getting late, and I probably am missing something stupid. 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=UTF-8" /> <title>Untitled Document</title> </head> <body> <?php $host = 'localhost'; $usr = "vinny"; $password = 'thepassword'; $db_name = 'logbook'; $date = $_POST['date']; $type = $_POST['type']; $reg_01 = $_POST['reg_01']; $reg_02 = $_POST['reg_02']; $captain = $_POST['captain']; $passenger = $_POST['passenger']; $where_01 = $_POST['where_01']; $where_02 = $_POST['where_02']; $takeoff_hr = $_POST['takeoff_hr']; $takeoff_min = $_POST['takeoff_min']; $landing_hr = $_POST['landing_hr']; $landing_min = $_POST['landing_min']; $ws_captain_hrs = $_POST['ws_captain_hrs']; $ws_captain_min = $_POST['ws_captain_min']; $ws_student_hrs = $_POST['ws_student_hrs']; $ws_student_min = $_POST['ws_student_min']; $3_captain_hrs = $_POST['3_captain_hrs'];// I have a problem with this line or where it inserts this into the DB??? /*$3_captain_min = $_POST['3_captain_min']; $3_student_hrs = $_POST['3_student_hrs']; $3_student_min = $_POST['3_student_min']; */ $errorstring = ""; // default value of errorstring if(isset($_POST['save_flight'])) { // Validate all the code inputs that are required fields if ($date =="") $errorstring = $errorstring. "Date<br>"; if ($type =="") $errorstring = $errorstring. "Aircraft Type<br>"; if ($reg_01 =="") $errorstring = $errorstring. "Reg Prefix<br>"; if ($reg_02 =="") $errorstring = $errorstring. "Registration Mark<br>"; if ($captain =="") $errorstring = $errorstring. "Captain<br>"; if ($where_01 =="") $errorstring = $errorstring. "Flight From<br>"; if ($where_02 =="") $errorstring = $errorstring. "Flight To<br>"; if ($takeoff_hr =="") $errorstring = $errorstring. "Takeoff Hours<br>"; if ($takeoff_min =="") $errorstring = $errorstring. "Takeoff Minutes<br>"; if ($landing_hr =="") $errorstring = $errorstring. "Landing Hours<br>"; if ($landing_min =="") $errorstring = $errorstring. "Landing Minutes<br>"; // does the errorstring = "nothing"? if ($errorstring !="") echo "You have not put anything in the following fields: <br><br> $errorstring"; //echo "If you have nothing to put in the box please type the word \"None\" or \"N\/A\""; //die ("Please try again, ensuring that you fill out all the fields!"); else { //echo "Your data has been saved"; //connect to database mysql_connect ("$host","$usr","$password") or die ('Error During Connect:<br>'.mysql_error()); mysql_select_db ("$db_name") or die ('Error Selecting DB:<br>'.mysql_error()); $insert_query = "INSERT INTO pilots_logbook (date, type, reg_01, reg_02, captain, passenger, where_01, where_02, takeoff_hr, takeoff_min, landing_hr, landing_min, ws_captain_hrs, ws_captain_min, ws_student_hrs, ws_student_min, 3_captain_hrs) VALUES ('$date', '$type', '$reg_01', '$reg_02', '$captain', '$passenger', '$where_01', '$where_02', '$takeoff_hr', '$takeoff_min', '$landing_hr', '$landing_min', '$ws_captain_hrs', '$ws_captain_min', '$ws_student_hrs', '$ws_student_min', '$3_captain_hrs')"; $insert_action = mysql_query($insert_query) or die ('Error During Insert :<br>'.mysql_error().'<br><br>Error occured running the following code :<br>'.$insert_query); $id = mysql_insert_id(); echo "Thank you, Your logbook entry has been saved."; } } ?> <p>Use this form to add an entry to your logbook.</p> <form name = "form1" method ="post" action=""> <table width="650" border="1" cellspacing="0" cellpadding="5"> <tr> <td>Required *</td> <td> </td> <td>This Format Only</td> </tr> <tr> <td width="180">Date *</td> <td width="300"> <input type="text" name="date" id="date" size = "25"/> </label> <input type="submit" name="today" id="today" value="Add Today" /></td> <td width="170">YYYY-MM-DD</td> </tr> <tr> <td>Aircraft Type *</td> <td><input type="text" name="type" id="type" size = "40" /></td> <td>E.G. Quantum</td> </tr> <tr> <td>Reg Number *</td> <td><input type="text" name="reg_01" id="reg_01" size = "5" /> - <input type="text" name="reg_02" id="reg_02" size = "15"/></td> <td>G - ABCD</td> </tr> <tr> <td>Captain *</td> <td><input type="text" name="captain" id="captain" size = "40" /></td> <td>Name of Captain</td> </tr> <tr> <td>Passenger or Student</td> <td><input type="text" name="passenger" id="passenger" size = "40" /></td> <td>Were you? P or S</td> </tr> <tr> <td>Flight From *</td> <td><input type="text" name="where_01" id="where_01" size = "40" /></td> <td>Take off Airfield</td> </tr> <tr> <td>Flight To *</td> <td><input type="text" name="where_02" id="where_02" size = "40" /></td> <td>Landing Airfield</td> </tr> <tr> <td>Takeoff GMT *</td> <td><label>Hr <input type="text" name="takeoff_hr" id="takeoff_hr" size = "10" /> Min <input type="text" name="takeoff_min" id="takeoff_min" size="10"/> </label></td> <td>24 Hr Format Only</td> </tr> <tr> <td>Landing GMT *</td> <td><label>Hr <input type="text" name="landing_hr" id="landing_hr" size="10" /> Min <input type="text" name="landing_min" id="landing_min" size="10" /> </label></td> <td>24 Hr Format Only</td> </tr> <tr> <td>Captain Weighshift</td> <td><label>Hrs <input type="text" name="ws_captain_hrs" id="ws_captain_hrs" size = "10"/></label> <label>Min <input type="text" name="ws_captain_min" id="ws_captain_min" size = "10" /> <input type="submit" name="autofill_ws_captain" id="autofill_ws_captain" value="Auto Insert" /> </label></td> <td>Button works it out and inserts it here</td> </tr> <tr> <td>Student Weightshift</td> <td><label>Hrs <input type="text" name="ws_student_hrs" id="ws_student_hrs" size = "10"/></label> <label>Min <input type="text" name="ws_student_min" id="ws_student_min" size="10" /> <input type="submit" name="autofill_ws_student" id="autofill_ws_student" value="Auto Insert" /> </label></td> <td>Button works it out and inserts it here</td> </tr> <tr> <td>Captain 3 Axis</td> <td><label>Hrs <input type="text" name="3_captain_hrs" id="3_captain_hrs" size = "10"/> </label> <label>Min <input type="text" name="3_captain_min" id="3_captain_min" size = "10" /> <input type="submit" name="autofill_3_captain" id="autofill_3_captain" value="Auto Insert" /> </label></td> <td>Button works it out and inserts it here</td> </tr> <tr> <td>Student 3 Axis</td> <td><label>Hrs <input type="text" name="3_student_hrs" id="3_student_hrs" size = "10"/> </label> <label>Min <input type="text" name="3_student_min" id="3_student_min" size = "10" /> <input type="submit" name="autofill_3_student" id="autofill_3_student" value="Auto Insert" /> </label></td> <td>Button works it out and inserts it here</td> </tr> <tr> <td>Passenger Interest Only</td> <td>Hrs <input type="text" name="passenger_only_hrs" id="passenger_only_hrs" size="10"/> Min <input type="text" name="passenger_only_mins" id="passenger_only_mins" size="10"/> <input type="submit" name="passenger_button" id="passenger_button" value="Auto Insert" /></td> <td>Button works it out and inserts it here</td> </tr> <tr> <td>Remarks</td> <td><textarea name="remarks" id="remarks" cols="45" rows="5"></textarea></td> <td>Went to get microlight forum cup from XYZ airfield. Maximum 500 characters</td> </tr> <tr> <td><input type="submit" name="save_flight" id="save_flight" value="Save Flight" /></td> <td><input type="submit" name="reset" id="reset" value="Reset Form" /></td> <td> </td> </tr> </table> <p> </p> <p> </p> </body> </html> Similar TutorialsI'm trying to add some data into my database through a form interface, but this form submits even when the page loads. This means the form submits regardless of the validation I have set in place, so every time the page is loaded, the database receives empty fields. Could you guys please help me with my problem? Here's my code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">; <html xmlns="http://www.w3.org/1999/xhtml">; <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Form to add quotes</title> </head> <body> <?php //defining variables $genre = ""; $error_quote=""; $error_author=""; $error_date=""; $error_url=""; $error_genre=""; $quote = ""; $author=""; $q_date=""; $url=""; $output_form = true; if (isset($_POST['submit'])) { $output_form = true; if (trim($quote)=='' OR strlen(trim($quote)) < 2 OR strlen(trim($quote)) > 16) { $error_quote="Please enter a <b>Quote</b> between 2 to 16 characters long <br/>"; } if(trim($author)=='' OR strlen(trim($author)) < 2 OR strlen(trim($author)) > 16) { $error_author="Please enter an <b>Author</b> between 2 to 16 characters long <br/>"; } if(trim($q_date)=='' OR strlen(trim($q_date)) < 2 OR strlen(trim($q_date)) > 24) { $error_date="Please enter a <b>Date</b> between 2 to 24 characters long <br/>"; } if(trim($url)=='' OR strlen(trim($url)) < 2 OR strlen(trim($url)) > 246) { $error_url="Please enter a <b>URL</b> between 2 to 246 characters long <br/>"; } if(!isset($genre) OR $genre=='') { $error_genre=" - Please select a <b>Genre</b>. <br/>"; } } else { $output_form = false; } if ($output_form) { ?> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <table> <tr><td>Quote</td><td><input type="text" name="quote" value="<?php if (isset($quote)) echo $quote ; ?>"></td><td><?php echo $error_quote;?></td></tr> <tr><td>Author</td><td><input type="text" name="author" value="<?php if (isset($author)) echo $author ; ?>"></td><td><?php echo $error_author;?></td></tr> <tr><td>Date</td><td><input type="text" name="q_date" value="<?php if (isset($q_date)) echo $q_date ; ?>"></td><td><?php echo $error_date;?></td></tr> <tr><td>URL</td><td><input type="text" name="url" value="<?php if (isset($url)) echo $url ; ?>"></td><td><?php echo $error_url;?></td></tr> </table> <p>Gen </p><p> <input type="radio" name="genre" value="humour" <?php if (isset($genre) AND $genre=="humour") echo $genre; ?> />Humour <?php echo $error_genre;?> <input type="radio" name="genre" value="politics" <?php if (isset($genre) AND $genre=="politics") echo $genre; ?> />Politics <?php echo $error_genre;?> <input type="radio" name="genre" value = "romance" <?php if (isset($genre) AND $genre=="romance") echo $genre; ?>/>Romance <?php echo $error_genre;?> </p> <p><input type = "submit" name="submit" value = "add quote" /></p> </form> <?php } $dbhost = 'localhost'; $dbuser = '...'; $dbpass = '...'; $dbname = 'anevins'; // make a connection to the database $conn = mysql_connect($dbhost, $dbuser, $dbpass) OR die('Connection failed: '. mysql_error()); // select the database mysql_select_db($dbname) OR die('Database select failed: '. mysql_error()); // set up the query to insert the new data $query = "INSERT INTO quotes (id, quote, author, q_date, url, genre) VALUES ('', '$quote', '$author', '$q_date', '$url', '$genre')"; $result = mysql_query($query) OR die('Query failed: ' . mysql_error()); echo "<p>Thank you for adding your quote</p>"; mysql_close($conn); exit(); ?> </body> </html> So i have an event page where it will show the next 3 events, then i need logged in users to click either of two buttons to say there attending or not attending. i have the below code showing events, and the <form> and the submit and both buttons, but if i submit 1 button on event ID: 1 it inserts data into the database but for event ID: 2, and if i click the button on event ID :2 it also puts it into database with eventid:2 so no matter which event i click it seems to submit data with the latest event ID shown on page, and not for "each" event seperatly. i have moved the submit query everywhere around and still same results or duplicate results if its in the loop. i assume its looping the submit and only submitting the latests event ID.
<?php if ($result = $con->query("SELECT * FROM events ORDER BY id ASC LIMIT 3")) { if ($result->num_rows > 0) { while ($row = $result->fetch_object()) { $event_id = $row->id; // set up table and echo data! echo "<table border='1' cellpadding='2' width='50%'>"; echo "<tr><td>"; echo "<p><img src='images/raid_banners/" . $row->bannerimg . "'>" . $row->name . " (iLvl: " . $row->itemlevel . ")</p>"; echo "<p>Event Starts: " . $row->datestart . " - " . $row->timestart . "</p>"; echo "<p>Event Ends: " . $row->dateend . " - " . $row->timeend . "</p>"; echo "<p>Raid Lead: " . $row->raidlead . "</p>"; echo "<form action='' name='$event_id' method='post'>"; // Process and populate SELECT form element echo "<select name=\"charname\">"; $sql = mysqli_query($con, "SELECT * FROM characters WHERE userid = $userid"); while ($row = $sql->fetch_assoc()){ echo "<option value=\"{$row['id']}\">{$row['charname']}</option>"; } echo "</select>"; echo "<input type='hidden' name='raidid' value ='$event_id'>"; echo "<input type='hidden' name='action' value='submit' />"; echo "<input type=\"submit\" name=\"submit\" value=\"going\">"; echo "<input type=\"submit\" name=\"submit\" value=\"notgoing\">"; echo "</form></td></tr></table><br><br>"; } if(isset($_POST['action'])){ $charid = $_POST['charname']; $submit = $_POST['submit']; // Submit the data from dropdown in the form mysqli_query($con,"INSERT INTO eventsignup (eventid, charid, userid, status) VALUES ('$event_id', '$charid', '$userid', '$submit')"); } } else { echo "No results to display!"; } } else { echo "Error: " . $con->error; } $con->close(); ?> any help would be awesome. im tearing my hair out here. 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"; } ?> Hi. I have a list of prices in my database - I.E: NAME ------------ PRICE ----------------------------- APPLE ------------- 1.00 PEAR --------------- 1.00 BANANA ----------- 1.92 ----------------------------- in php i want to add the tables data together to show a total price for that columns data. I.E: Total cost: 3.92 How on earth do I do this? :S! Many Thanks nevermind. Hi everyone, Hope someone can help. Does anyone know why this is nor displaying any data? Code: [Select] $qry = mysql_query("select * from product"); $data = array(); while($row = mysql_fetch_array($qry)){ $productName[] =$row['productName']; // Item name } for($i=0;$i<mysql_num_rows($row);$i++) { $data = $productName[$i]; } return $data; Thanks in advance Edd hey everyone! in new to the whole php and mysql thing and i am stuck with one part, i have got a login script, once loged in it takes them to there account page, on there account page they can added data into there file, to mysql, so what I'm looking for is how to add the username they logged in with to be added into the database with the rest of the information they just submitted, so when they go to retrieve there information into a table they will only get the information that has there username with it. as much help as possible would be great! thank-you I have two tables 'book' and 'category'. They look like the following in phpmyadmin;
book
id title author category isbn ---- ------- ---------- ---------- ------- 1 Treasure Chest Jim Jones 1 14252637 2 Pirates Boat Sue Smith 2 88447737 3 Adventure Land Harry Jo 3 01918273 4 Winter Week Sam Dill 3 00999337 5 The Twite Roald Dahl Fiction 87873366 category id cat_name ---- ------- 1 Horror 2 Kids 3 Fiction 4 Science Users have the option of adding books into the library via an online form, or via a Google Booka api method (user enters isbn, searches, is presented with book info and then clicks 'add to library', done.). This is handled via ajax. The online form works fine, and successfully adds the book info. However my problem is with the Google Books method, it successfully adds the data to the db however the category column is in text format (i.e 'Juvenile Science' or 'Scary Fiction') as opposed to the manual form which adds categories as 1, 2 or 3 (1 =Horror, 2 = Kids, 3 = Fiction). Is there any way I can add the Google Book category data to my table and convert it to an integer or similar? Not sure what I need to do. Suggestions appreciated! Should I add the Google entries to another table (i.e googleCategory)? My HTML only outputs the numbered category entries and ignored the text format entries. my php $sql = "SELECT b.id, b.title, b.author, b.isbn, b.publicationYear, c.cat_name FROM book AS b INNER JOIN category AS c ON b.category = c.id WHERE status != 'Archive' ORDER BY id DESC LIMIT $startrow, 15 "; $res = $conn->query($sql) or trigger_error($conn->error."[$sql]"); while($row = $res->fetch_array()) { echo '<tbody>'; echo '<tr>'; echo '<td>' . $row['id'] . '</td>'; echo '<td>' . $row['title'] . '</td>'; echo '<td>' . $row['author'] . '</td>'; echo '<td>' . $row['cat_name'] . '</td>'; echo '<td>' . $row['isbn'] . '</td>'; echo '<td>' . $row['publicationYear'] . '</td>'; echo '</tr>'; echo '</tbody>'; };Apologies if this is all a bit confusing I am very new to php and mysql. Thanks, J Hi I have currently written some code which uses of the Twitter API and extracts the information required to display my most current tweet on my website. This is all working perfectly but at the minute it is only displaying one tweet and I would like it to display as many as the variable $limit is set to. I have tried numerous count with while loops but just cannot seem to get my head around the logic of it. Here is the code im currently using which displays one tweet. <?php $username = "my_twitter_username"; $limit = "2"; $twitter_url = "http://twitter.com/statuses/user_timeline/$username.xml?count=$limit"; $buffer = file_get_contents($twitter_url); $xml = new SimpleXMLElement($buffer); $status_item = $xml -> status; $status_id = $xml -> status -> id; $user_item = $xml -> status -> user; $user_id = $xml -> status -> user -> screen_name; $description = $status_item -> text; $status_time = $status_item -> created_at; $status_img = $user_item -> profile_image_url; $description = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $description); $description = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $description); $description = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $description); $description = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=%23\\1\" target=\"_blank\">#\\1</a>", $description); echo " <div class='tweet-wrapper'> <div class='tweet-img'> <a href='http://www.twitter.com/la__academia' target='_BLANK'><img src='$status_img' alt='La Academia Twitter' style='width:30px height:30px;' /></a> </div><!-- tweet-img --> <div class='tweet-text'> <p class='tweet-p'>$description</p> <p class='tweet-time'>$status_time . <a href='http://twitter.com/?status=@$user_id%20&in_reply_to_status_id=$status_id&in_reply_to=$user_id' target='_BLANK' class='tweet-reply'>Reply</a></p> </div><!-- tweet-text --> <div class='cleaner'></div> </div><!-- tweet-wrapper --> "; ?> Thanks for any help. I have MySQL table with the following fields: user=>varchar product=>varchar Amount=>int Date=>date Note=>tinytext I can't add value to these field by the following php code: $date = date("Y.m.d"); $query = "INSERT INTO order VALUES ('farhad', 'Mango', '10', '$date', 'hello')"; $result = mysql_query($query) or die(mysql_error()); I receive the following warning: Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Paris' for '2.0/DST' instead in C:\inetpub\wwwroot\Okern\~order.php on line 10 Call Stack: 0.0047 325856 1. {main}() C:\inetpub\wwwroot\Okern\~order.php:0 0.0274 344912 2. date() C:\inetpub\wwwroot\Okern\~order.php:10 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 'order VALUES ('farhad', 'Mango', '10', '2011.04.17', 'hello')' at line 1 Hi, I'm making a website that uses data stored in SQL. One of my pages allows the user to enter a new product into a product table. I was wondering if somebody could help me with some validation or Query that will not allow the user to enter a product name that already exists in the table? Code: [Select] $nameNew = $_POST['new]; $nameID = $_POST['newID]; $namePrice = $_POST['newPrice]; INSERT INTO products VALUES ($nameNew, $newID, $newPrice) $describeQuery = "SELECT ID, Name, Price FROM Products"; $results = sqlsrv_query($conn, $describeQuery); echo '<table border="1" BORDERCOLOR=Black>'; echo '<tr><th bgcolor = "LightBlue">Name</th><th bgcolor = "LightBlue" >ID</th> <th bgcolor = "LightBlue" >Price</th></tr>'; while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC)) { echo '<tr>'; echo '<td >' .$row['Name'].'</td>'; echo '<td>' .$row['ID'].'</td>'; echo '<td>' .$row['Price'].'</td>'; echo '</tr>'; } echo '</table>'; sqlsrv_close($conn); Thanks So I have to add data into my database for Olympic records for a school project. I have the sql statements and everything, but it will only enter the athlete's name and country into the table. My code is Code: [Select] <html> <head> <title> CSS </title> <style type="text/css"> p {font-family:arial; font-size:10pt;} body {margin: 0; padding: 0; text-align: center;} a:link {text-decoration: none} a:visited {text-decoration: overline; color:purple;} a:active {text-decoration: underline;} a:hover {text-decoration: line-through ; color:pink} input:hover {background: aqua; color:black} input:active { background: lime ; color: black; } input:focus { background: yellow; color: black; } .button {border: 1px dotted ; background:red; padding: 2px;} .button:hover {border: 2px dotted;background: url('submitbackground.jpg') no-repeat top left; } #main {margin: 0 auto; text-align: left; width: 800px;} #nav {clear: both; border: 1px solid; background-color:lightgreen; padding: 10px; width:auto; height: 8%;} #div1 {border: 1px solid; background-color:lightblue; padding: 10px; float: left; width:20%; height:92%;} #div2 {border: 1px solid; background-image: url('monkey.jpg'); background-repeat:no-repeat; background-position:center bottom ; padding: 10px; float:left; width:74.5%; height:92%;} </style> </head> <body> <?php session_start () ; print_r ($_REQUEST) ; if ($_SESSION['admin'] == 2) { echo " sorry" ; } else { echo $_SESSION['admin']; if(isset($_POST['athname'])){ $athname= $_POST['athname'] ; } if(isset($_POST['country'])){ $country = $_POST['country']; } if(isset($_POST['medal'])){ $medal= $_POST ['medal']; } if(isset($_POST['venueyear'])){ $venueyear= $_POST ['venueyear']; } if(isset($_POST['venuecity'])){ $venuecity= $_POST ['venuecity']; } if(isset($_POST['venuecountry'])){ $venuecountry= $_POST ['venuecountry']; } if(isset($_POST['event'])){ $event= $_POST ['event']; } if(isset($_POST['gender'])){ $gender= $_POST ['gender']; } echo "<div id='main'> " ; echo"<div id='nav'>"; echo"</div>" ; echo "<div id='div1'>" ; echo "<a href='index.php'>home</a><br/>" ; echo "<a href='search.php'>Search</a><br/>" ; echo "<a href='add-data.php'>Add Data</a><br/>" ; echo "<a href='DeleteData.php'>Delete Data</a>" ; echo "</div>" ; echo"<div id='div2'>" ; if (isset($_POST['search'])) { $connection = odbc_connect('Olympics', '', ''); if (!$connection) {exit("Conection Failed: " . $connection);} $enrID = null ; if ( $event == '100 meters' and $gender == 'M') { $enrID = 1 ; echo "$enrID" ; }elseif ($event == '200 meters' and $gender == 'M') { $enrID = 2 ; echo "$enrID" ; }elseif ($event == '400 meters'and $gender == 'M') { $enrID = 3 ; }elseif ($event == '800 meters' and $gender == 'M') { $enrID = 4 ; }elseif ($event == '1500 meters' and $gender == 'M') { $enrID = 5 ; }elseif ($event == 'Long Jump' and $gender == 'M') { $enrID = 6 ; }elseif ($event == 'High Jump' and $gender == 'M') { $enrID = 7 ; }elseif ($event == 'Shot put' and $gender == 'M') { $enrID = 8 ; }elseif ($event == 'basketball' and $gender == 'M') { $enrID = 13 ; }elseif ($event == 'rowing' and $gender == 'M') { $enrID = 14 ; }elseif ($event == 'volleyball(indoor)' and $gender == 'M') { $enrID = 15 ; }elseif ($event == 'volleyball(beach)' and $gender == 'M') { $enrID = 16 ; }elseif ($event == '100 meters' and $gender == 'F') { $enrID = 17 ; }elseif ($event == '200 meters' and $gender == 'F') { $enrID = 18 ; }elseif ($event == '400 meters'and $gender == 'F') { $enrID = 19 ; }elseif ($event == '800 meters' and $gender == 'F') { $enrID = 20 ; }elseif ($event == '1500 meters' and $gender == 'F') { $enrID = 21 ; }elseif ($event == 'Long Jump' and $gender == 'F') { $enrID = 22 ; }elseif ($event == 'High Jump' and $gender == 'F') { $enrID = 23 ; }elseif ($event == 'Shot put' and $gender == 'F') { $enrID = 24 ; }elseif ($event == 'basketball' and $gender == 'F') { $enrID = 25 ; }elseif ($event == 'rowing' and $gender == 'F') { $enrID =26 ; }elseif ($event == 'volleyball(indoor)' and $gender == 'F') { $enrID = 27 ; }elseif ($event == 'volleyball(beach)' and $gender == 'F') { $enrID = 28 ; } $EnrVenID = null ; if ($venueyear == '1984') { $EnrVenID = 1 ; echo "$EnrVenID" ; }elseif ($venueyear == '1988') { $EnrVenID = 2 ; }elseif ($venueyear == '1992') { $EnrVenID = 3 ; }elseif ($venueyear == '1996') { $EnrVenID = 4 ; }elseif ($venueyear == '2000') { $EnrVenID = 5 ; }elseif ($venueyear == '2004') { $EnrVenID = 6 ; }elseif ($venueyear == '2008') { $EnrVenID = 7 ; echo "$EnrVenID" ; }elseif ($venueyear == '2012') { $EnrVenID = 8 ; echo "$EnrVenID" ; } $sql="INSERT INTO Athletes (Athname, Athcountry) values ( '$athname', '$country') " ; $rs=odbc_exec($connection,$sql); $sql4="INSERT INTO Enrollments (EnrMedal, EnrYear, EnrEventID, EnrVenID) values ( '$medal', '$venueyear', '$enrID', '$EnrVenID') " ; $rs4=odbc_exec($connection,$sql4); } echo "<form method='post' action=''>\n"; echo"Please fill out all the fields with the data that you wish to be added: <br/>"; echo"Athelete Name:<input type ='text' Name='athname' > <br/> \n" ; echo"Athelete Country:<input type ='text' Name='country' > <br/> \n" ; echo "Medal: <select name='medal' value='medal'>\n"; echo "<option > </option>\n"; echo "<option $Gold> Gold </option>\n"; echo "<option $Silver> Silver </option>\n"; echo "<option $Bronze'> Bronze</option>\n"; echo "</select>\n" ; echo "Venue Year: <select name='venueyear' value= 'venueyear'>\n"; echo "<option ></option>\n"; echo "<option $1984> 1984 </option>\n"; echo "<option $1988> 1988 </option>\n"; echo "<option $1992>1992 </option>\n"; echo "<option $1996> 1996 </option>\n"; echo "<option $2000> 2000 </option>\n"; echo "<option $2004> 2004 </option>\n"; echo "<option $2008> 2008 </option>\n"; echo "<option $2012> 2012</option>\n"; echo "</select>\n" ; echo "Venue City: <select name='venuecity' value= 'venuecity'>\n"; echo "<option > </option>\n"; echo "<option $LA> Los Angeles </option>\n"; echo "<option $Seoul> Seoul </option>\n"; echo "<option $Barca> Barcelona </option>\n"; echo "<option $ATL> Atlanta</option>\n"; echo "<option $Syd> Sydney </option>\n"; echo "<option $Ath> Athens</option>\n"; echo "<option $Beij> Beijing </option>\n"; echo "<option $Lon> London</option>\n"; echo "</select>\n" ; echo "Venue City: <select name='venuecountry' value= 'venuecountry'>\n"; echo "<option > </option>\n"; echo "<option $USA> U.S.A. </option>\n"; echo "<option $SK> South Korea </option>\n"; echo "<option $Spain> Spain </option>\n"; echo "<option $Aus> Australia </option>\n"; echo "<option $Greece> Greece</option>\n"; echo "<option $Chin> China </option>\n"; echo "<option $UK> United Kingdom</option>\n"; echo "</select>\n" ; echo "Event: <select name='event' value='event>\n"; echo "<option value=''> </option>\n"; echo "<option > </option>\n"; echo "<option $100m> 100 meters</option>\n"; echo "<option $200m> 200 meters </option>\n"; echo "<option $400m>400 meters </option>\n"; echo "<option $800m> 800 meters </option>\n"; echo "<option $1500m> 1500 meters </option>\n"; echo "<option $LongJump> Long Jump</option>\n"; echo "<option $HighJump> High Jumo </option>\n"; echo "<option $Shotput> Shot put </option>\n"; echo "<option $Basketball> Basketball </option>\n"; echo "<option $Rowing> Rowing </option>\n"; echo "<option $Volleyball> Indoor Volleyball </option>\n"; echo "<option $Volley> Beach Volleyball</option>\n"; echo "</select>\n" ; echo "Gender: <select name='gender'>\n"; echo "<option value=''> </option>\n"; echo "<option $Male>M</option>\n"; echo "<option $Female>F</option>\n"; echo "</select>\n" ; echo "<input type='submit' name='search' value='Search' />\n"; echo "</form>\n"; echo "</div>" ; } ?> </body> </html> I have the really long IF statements in there so that it enters the correct EnrID and EnrVenID into the database, to make sure it fills out all fields. I am using Microsoft access for my database. The problem is that it will only fill in the athlete's name and country, and not his/her enrollment information (what medal they got, their enr ID, what year it was taken place, etc. The problem with my login system is that I want the user to login with a username and password if they wish to be an admin, but the login system doesn't work. the variables aren't passed through the system for some reason, even though it worked a week ago, but now it doesn't. The code is Code: [Select] if(isset($_POST['username'])){ $username= $_POST['username'] ; } if(isset($_POST['password'])){ $password= $_POST['password'] ; } $username = null ; $password = null ; Thanks for any help Am new here - looks like a great foru! I would sincerely appreciate any help anyone can give me. I have been trying to solve my problem for hours and I am not having any luck, so I thought I would post and see if anyone can help. I am very stuck and am not making much progress on this project, and I am certain the answer is very simple. I am constructing a form to collect data for a specialized purpose. The form and program actually work for its intended function, but I am trying to enhance the user experience by preventing customers from having to reenter all of their data should there be a problem with any of the data submitted. I have been able to do that with the contact form portion, but what I am having trouble with is the portion which has as many as 400 possible entries. So, in a nutshell, if the customers contact data is incomplete or in error, the form will ask them to return to the page and correct things. The previous data entered has been saved in the session and the input value will equal the previous entry. i.e. <tr> <td align="right" class="infoBox"><?php echo ENTRY_EMAIL_ADDRESS; ?></td> <td align=left><?php echo "<input type=text name='cemail' value=\"$cemail\" size=35 maxlength=35>" ?></td> </tr> Works perfectly, all well and good there. On the other 400 more or less entries, I am having a difficult time tweaking the string concatenation to work to achieve similar results. There are 4 columns each with $points entries asking for a dimension in either feet or inches. The <input name=> is one of ptaf,ptai,ptbf,ptbi, appended programatically with the corresponding row number or data point. i.e. "ptaf1", "ptai1", etc... This is produced by the example below and works perfectly also. <?php { $points=100; $i=1; while ($i <= $points) {echo ' <tr><td align="center" width="6"><b> ' .$i . '</b></td> <td align="right" NOWRAP>A' .$i . ' (ft) <input type="text" name="ptaf'.$i.'" size=4 maxlength=3> </td> <td align="right" NOWRAP>A' .$i . ' (in) <input type="text" name="ptai'.$i.'" size=4 maxlength=4> </td> <td align="right" NOWRAP>B' .$i . ' (ft) <input type="text" name="ptbf'.$i.'" size=4 maxlength=3> </td> <td align="right" NOWRAP>B' .$i . ' (in) <input type="text" name="ptbi'.$i.'" size=4 maxlength=4> </td> '; $i++; } } ?> I am trying to add <input value=$ptai.$i> for each field but as I mentioned I am not having any luck. It seems as if I have tried every combination imagineable, but still no luck. My head is spinning! The closest I seem to have gotten was with this: <td align="right" NOWRAP>A' .$i . ' (ft) <input type="text" size=6 maxlength=3 name="ptaf'.$i.'" value="' . "$ptaf" . $i . '" ></td> But line 17 for example returns this: <input type="text" value="17" name="ptaf17" maxlength="3" size="6"> To recap, I am trying to have the value set to whatever the customer may have entered previously. Again, I would most appreciate any help anyone can give me. If you need clarification on anything please let me know. Thanks AJ Say there is a complex opt in process where people start to enter their data but certain questions stop them where they close out of the page. They already entered their data and I feel there is a way to grab it and post it to mysql even though they do not click submit.
How would this be done?
A super simple example (proof of concept) or a link to a tutorial would be very useful.
Edited by brentman, 23 September 2014 - 10:42 AM. Greetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> Hello, I have coded a contact form in PHP and I want to know, if according to you, it is secure! I am new in PHP, so I want some feedback from you. Moreover, I have also two problems based on the contact form. It is a bit complicated to explain, thus, I will break each of my problem one by one. FIRST:The first thing I want to know, is if my contact form secure according to you: The HTML with the PHP codes: Code: [Select] <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { //Assigning variables to elements $first = htmlentities($_POST['first']); $last = htmlentities($_POST['last']); $sub = htmlentities($_POST['subject']); $email = htmlentities($_POST['email']); $web = htmlentities($_POST['website']); $heard = htmlentities($_POST['heard']); $comment = htmlentities($_POST['message']); $cap = htmlentities($_POST['captcha']); //Declaring the email address with body content $to = 'alithebestofall2010@gmail.com'; $body ="First name: '$first' \n\n Last name: '$last' \n\n Subject: '$sub' \n\n Email: '$email' \n\n Website: '$web' \n\n Heard from us: '$heard' \n\n Comments: '$comment'"; //Validate the forms if (empty($first) || empty($last) || empty($sub) || empty($email) || empty($comment) || empty($cap)) { echo '<p class="error">Required fields must be filled!</p>'; header ('refresh= 3; url= index.php'); return false; } elseif (filter_var($first, FILTER_VALIDATE_INT) || filter_var($last, FILTER_VALIDATE_INT)) { echo '<p class="error">You cannot enter a number as either the first or last name!</p>'; return false; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo '<p class="error">Incorrect email address!</p>'; return false; } elseif (!($cap === '12')){ echo '<p class="error">Invalid captcha, try again!</p>'; return false; } else { mail ($to, $sub, $body); echo '<p class="success">Thank you for contacting us!</p>'; } } ?> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <p>Your first name: <span class="required">*</span></p> <p><input type="text" name="first" size="40" placeholder="Ex: Paul"/></p> <p>Your last name: <span class="required">*</span></p> <p><input type="text" name="last" size="40" placeholder="Ex: Smith"/></p> <p>Subject: <span class="required">*</span></p> <p><input type="text" name="subject" size="40" placeholder="Ex: Contact"/></p> <p>Your email address: <span class="required">*</span></p> <p><input type="text" name="email" size="40" placeholder="Ex: example@xxx.com"/></p> <p>Website:</p> <p><input type="text" name="website" size="40" placeholder="Ex: http//:google.com"/></p> <p>Where you have heard us?: <span class="required">*</span></p> <p><select name="heard"> <option>Internet</option> <option>Newspapers</option> <option>Friends or relatives</option> <option>Others</option> </select></p> <p>Your message: <span class="required">*</span></p> <p><textarea cols="75" rows="20" name="message"></textarea></p> <p>Are you human? Sum this please: 5 + 7 = ?: <span class="required">*</span></p></p> <p><input type="text" name="captcha" size="10"/></p> <p><input type="submit" name="submit" value="Send" class="button"/> <input type="reset" value="Reset" class="button"/></p> </form> SECOND PROBLEM:If a user has made a mistake, he gets the error message so that he can correct! However, when a mistake in the form occurs, all the data the user has entered are disappeared! I want the data to keep appearing so that the user does not start over again to fill the form. THIRD: When the erro message is displayed to notify the user that he made a mistake when submitting the form, the message is displaying on the top of the page. I want it to appear below each respective field. How to do that? In JQuery it is simple, but in PHP, I am confusing! There are two pieces to this- The HTML Form and the resulting php. I can't seem to make the leap, from the code to having the form produce the php page so others can view it until the form is again submitted overwriting the php, thus generating new content. The environment I am working in is limited to IIs 5.1 and php 5.2.17 without mySQL or other DB I'm new to php, this isn't homework,or commercialization, it's for children. I am thinking perhaps fwrite / fread but can't get my head around it. Code snipets below. Any help, please use portions of this code in hopes I can understand it Thanks Code snipet from Output.php Code: [Select] <?php $t1image = $_POST["t1image"]; $t1title = $_POST["t1title"]; $t1info = $_POST["t1info"]; $t2image = $_POST["t2image"]; $t2title = $_POST["t2title"]; $t2info = $_POST["t2info"]; ?> ... <tbody> <tr><!--Headers--> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Animal</td> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Image thumb<br> </td> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Date<br> </td> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Information<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: center;">Monkey </td> <td style="vertical-align: top; text-align: center;"><img src="<?php echo $t1image.'.gif'; ?>"><!--single image presented selected from radio buttons--> </td> <td style="vertical-align: top; text-align: center;"><?php echo date("m/d/Yh:i A"); ?><!--time stamp generated when submitted form populates all fields at once--> </td> <td style="vertical-align: top; text-align: center;"><a href="#monkey" rel="facebox"><?php echo $t1title ?></a><!--Link name provided by "Title 1", that links to hidden Div generated page with content from "Info1" field--> <div id="Monkey" style="display:none"> <?php echo $t1info; ?> </div> </td> </tr> <tr> <td style="vertical-align: top; text-align: center;">Cat<br> </td> <td style="vertical-align: top; text-align: center;"><img src="<?php echo $t2image.'.gif'?>"></td> <td style="vertical-align: top; text-align: center;"><?php echo date("m/d/Yh:i A"); ?></td> <td style="vertical-align: top; text-align: center;"><a href="#Cat" rel="facebox"><?php echo $t2title ?></a> <div id="Cat" style="display:none"> <?php echo $t2info; ?> </div> </td> </tr> <tr> This replicates several times down the page around 15-20 times ( t1### - t20###) Code Snipet from HTML Form Code: [Select] <form action="animals.php" method="post"> <div style="text-align: left;"><big style="font-family: Garamond; font-weight: bold; color: rgb(51, 51, 255);"><big><big><span>Monkey</span></big></big></big><br> <table style="text-align: left; width: 110px;" border="0" cellpadding="2" cellspacing="0"> <tbody><tr> <td style="vertical-align: top;">Image thumb<br> <input type="radio" name="t1image" value="No opinion" checked><img src="eh.gif" alt="Eh"> <input type="radio" name="t1image" value="Ok"><img src="ok.gif" alt="ok"> <input type="radio" name="t1image" value="Like"><img src="like.gif" alt="Like"> <input type="radio" name="t1image" value="Dont"><img src="dont.gif" alt="Don't Like"> <input type="radio" name="t1image" value="Hate"><img src="hate.gif" alt="Hate"> <input type="radio" name="t1image" value="Other"><img src="other.gif" alt="Other"> <br> Why Title:<input type="text" name="t1title" size="45" value="..."/></td> <td style="vertical-align: top;"> Explain:<br> <textarea name="t1info" cols=45 rows=3 value="..."></textarea> </td></tr></table> <br> <!--Next--> How do I get the Form data to save to the php page for others to view? I have an email form that can have comma separated email addresses. I need to modify my code such that initially if the form does not contain any value, it should let me add email addresses to it. When I enter the web page next time it should display and let me edit the existing email addresses. Here is my code below. Right now it does not insert anything the first time. Code: [Select] <? error_reporting(E_ALL & ~E_NOTICE); $conn = mysql_connect('localhost','test','*****') or trigger_error("SQL", E_USER_ERROR); $db = mysql_select_db('test',$conn) or trigger_error("SQL", E_USER_ERROR); //$sql=mysql_query("SELECT * from new_database") or die(mysql_error()); $getemail=mysql_query("SELECT * from email") or die(mysql_error()); if(mysql_num_rows($getemail) > 0) { while($getemail_results=mysql_fetch_assoc($getemail)) { $getemailadd=$getemail_results['email']; } } else { $getemailadd=''; } if (!isset($_POST['submit'])) { ?> <b>ADDING A Email</b><br> <form action="<?php echo $PHP_SELF;?>" method="post"> Email:<br> <input type="text" size ="80" name="email" value="<?PHP if(isset($getemailadd)){ echo $getemailadd; } ?>" /><br> <input type="submit" name="submit" value="submit" /> </form> <? } else { // Get values from form $email=$_POST['email']; //$sql=mysql_query("INSERT into email(email)VALUES('$email')") or die (mysql_error()); $sql=mysql_query("UPDATE email SET email='$email'") or die (mysql_error()); header('Location: index.php'); } ?> Hi, I have this PHP code which displays a form input, but I cannot work out how to add this javascript to the text field. PHP: <?php $data = '<div class="ui-widget infoBoxContainerSearch">' . ' <div class="ui-widget-contentSearch infoBoxContentsSearch" style="text-align: center;">' . ' <div style="text-align: center;">' . tep_draw_form('quick_find', tep_href_link(FILENAME_ADVANCED_SEARCH_RESULT, '', 'NONSSL', false), 'get') . '' . ' ' . tep_draw_input_field('keywords', '') . ' ' . tep_draw_hidden_field('search_in_description', '1') . tep_hide_session_id() //. tep_image_submit('search_icon.png', MODULE_BOXES_SEARCH_BOX_TITLE) . '</div>' . ' </form>' . ' </div>' . '</div>'; echo $data; ?> JavaScript: value="Search" onfocus="this.value==this.defaultValue?this.value='':null" onblur="this.value==''?this.value=this.defaultValue:null;" Could anyone point me in the right direction? Thanks I have a basic question for anyone that can help me. Ive added a captcha input field to the form below, as Im having problems with spam appearing on my testimonial page. 1) How can I prevent the form from being sent if the wrong or no answer is in the form field. 2) How can i have a message appear saying "Sorry wrong answer" if the from isnt sent for the above reason? add.php Code: [Select] <form method="post" action="process2.php" > <textarea rows="25" cols="100" wrap="physical" name="data"> </textarea> <input type="hidden" name="area" value="testimonial"/> What is 5+5? <input type="text" name="captcha"/> <input type="submit" value="Add "> </form> process2.php Code: [Select] <p class="add">Thankyou for submitting your testimonial;</br> <?php $data="<br><br>" . $_POST["data"]; ?><br /> <?php $area=$_POST["area"]; ?> <?php echo $data; ?></p> <?php mysql_query("UPDATE wheelchairwizard SET data = CONCAT(data, '$data') WHERE area = '$area'"); ?> </br> Return to the testimonial page - <a href="http://www.wheelchairwizard.co.uk/testimonials.php">click here</a> |