PHP - Not Adding Data To Db
nevermind.
Similar TutorialsHi. 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 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> 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 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 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 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'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 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 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 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. 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); ?> Using curl_multi, I have loaded up 3 url's and then printed the array. 1) How can I also set a timestamp on output to let me know when each url was run? 2) How can I explode the array to only display the data and timestamp, excluding the text "Array ( =>", "[1] =>", "[2] =>" and " )"? Code <?php function multiRequest($data, $options = array()) { // array of curl handles $curly = array(); // data to be returned $result = array(); // multi handle $mh = curl_multi_init(); // loop through $data and create curl handles // then add them to the multi-handle foreach ($data as $id => $d) { $curly[$id] = curl_init(); $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d; curl_setopt($curly[$id], CURLOPT_URL, $url); curl_setopt($curly[$id], CURLOPT_HEADER, 0); curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1); // post? if (is_array($d)) { if (!empty($d['post'])) { curl_setopt($curly[$id], CURLOPT_POST, 1); curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']); } } // extra options? if (!empty($options)) { curl_setopt_array($curly[$id], $options); } curl_multi_add_handle($mh, $curly[$id]); } // execute the handles $running = null; do { curl_multi_exec($mh, $running); } while($running > 0); // get content and remove handles foreach($curly as $id => $c) { $result[$id] = curl_multi_getcontent($c); curl_multi_remove_handle($mh, $c); } // all done curl_multi_close($mh); return $result; } $data = array(array(),array()); $data[0]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Pearl+Jam&output=json'; $data[1]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Black+Eyed+Peas&output=json'; $data[2]['url'] = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Nirvana&output=json'; $r = multiRequest($data); print_r($r); ?> Output Array ( => Pearl Jam [1] => Black Eyed Peas [2] => Nirvana ) Preferred Output 01:00:01 Pearl Jam 01:00:02 Black Eyed Peas 01:00:03 Nirvana 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 Hello to all, I have problem figuring out how to properly display data fetched from MySQL database in a HTML table. In the below example I am using two while loops, where the second one is nested inside first one, that check two different expressions fetching data from tables found in a MySQL database. The second expression compares the two tables IDs and after their match it displays the email of the account holder in each column in the HTML table. The main problem is that the 'email' row is displayed properly while its while expression is not nested and alone(meaning the other data is omitted or commented out), but either nested or neighbored to the first while loop, it is displayed horizontally and the other data ('validity', 'valid_from', 'valid_to') is not displayed.'
Can someone help me on this, I guess the problem lies in the while loop? <thead> <tr> <th data-column-id="id" data-type="numeric">ID</th> <th data-column-id="email">Subscriber's Email</th> <th data-column-id="validity">Validity</th> <th data-column-id="valid_from">Valid From</th> <th data-column-id="valid_to">Valid To</th> </tr> </thead> Here is part of the PHP code:
<?php while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo ' <tr> <td>'.$row["id"].'</td> '; while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)) { echo ' <td>'.$row1["email"].'</td> '; } if($row["validity"] == 1) { echo '<td>'.$row["validity"].' month</td>'; }else{ echo '<td>'.$row["validity"].' months</td>'; } echo ' <td>'.$row["valid_from"].'</td> <td>'.$row["valid_to"].'</td> </tr>'; } ?>
Thank you. Hi, after banging my head against the wall for a while thinking this would be a simple task, I'm discovering that this is more complicated than I thought. Basically what I have is a link table linking together source_id and subject_id. For each subject there are multiple sources associated with each. I had created a basic listing of sources by subject... no problem. I now need a way of having a form to create an ordered list in a user-specified way. In other words, I can currently order by id or alphabetically (subject name lives on a different table), but I need the option of choosing the order in which they display. I added another row to this table called order_by. No problem again, and I can manage all of this in the database, however I want to create a basic form where I can view sources by subject and then enter a number that I can use for sorting. I started off looping through each of the entries and the database (with a where), and creating a foreach like so (with the subject_id being grabbed via GET from the URL on a previous script) Code: [Select] while($row = mysqli_fetch_array($rs)) { //update row order if (isset($_POST['submit'])) { //get variables, and assign order $subject_id = $_GET['subject_id']; $order_by = $_POST['order_by']; $source_id = $row['source_id']; //echo 'Order by entered as ' . $order_by . '<br />'; foreach ($_POST['order_by'] as $order_by) { $qorder = "UPDATE source_subject set order_by = '$order_by' WHERE source_id = '$source_id' AND subject_id = '$subject_id'"; mysqli_query($dbc, $qorder) or die ('could not insert order'); // echo $subject_id . ', ' . $order_by . ', ' . $source_id; // echo '<br />'; } } else { $subject_id = $_GET['subject_id']; $order_by = $row['order_by']; $source_id = $row['source_id']; } And have the line in the form like so: Code: [Select] echo '<input type="text" id="order_by" name="order_by[]" size="1" value="'. $order_by .'"/> (yes I know I didn't escape the input field... it's all stored in an htaccess protected directory; I will clean it up later once I get it to work) This, of course, results in every source_id getting the same "order_by" no matter what I put into each field. I'm thinking that I need to do some sort of foreach where I go through foreach source_id and have it update the "order_by" field for each one, but I must admit I'm not sure how to go about this (the flaws of being self-taught I suppose; I don't have anyone to go to on this). I'm hoping someone here can help? Thanks a ton in advance 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. I have two tables. Table Name:Users Fields: User_name user_email user_level pwd 2.Reference Fields: refid username origin destination user_name in the users table and the username field in reference fields are common fields. There is user order form.whenever an user places an order, refid field in reference table will be updated.So the user will be provided with an refid Steps: 1.User needs to log in with a valid user id and pwd 2.Once logged in, there will be search, where the user will input the refid which has been provided to him during the time of order placement. 3.Now User is able to view all the details for any refid 3.Up to this we have completed. Query: Now we need to retrieve the details based on the user logged in. For eg: user 'USER A' has been provided with the referenceid '1234' during the time of order placement user 'USER B' has been provided with the referenceid '2468' during the time of order placement When the userA login and enter the refid as '2468' he should not get any details.He should get details only for the reference ids which is assigned to him. <?php session_start(); if (!$_SESSION["user_name"]) { // User not logged in, redirect to login page Header("Location: login.php"); } $con = mysql_connect('localhost','root',''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("login", $con); $user_name = $_POST['user_name']; $refid = $_POST['refid']; $query = "SELECT * from reference,users WHERE reference.username=users.user_name AND reference.refid='$refid' AND "; $result = mysql_query($query) or trigger_error('MySQL encountered a problem<br />Error: ' . mysql_error() . '<br />Query: ' . $query); while($row = mysql_fetch_array($result)) { echo $row['refid']; echo $row['origin']; echo $row['dest']; echo $row['date']; echo $row['exdate']; echo $row['username']; } echo "<p><a href=\"logout.php\">Click here to logout!</a></p>"; ?> <html> <form method="post" action="final.php"> Ref Id:<input type="text" name="refid"> <input type="submit" value="submit" name="submit"> </html> 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 { } Here's the code that deals with the client side:
<?php session_start(); if(!isset($_SESSION['Logged_in'])){ header("Location: /page.php?page=login"); } ?> <!DOCTYPE Html> <html> <head> <!--Connections made and head included--> <?php require_once("../INC/head.php"); ?> <?php require_once("../Scripts/DB/connect.php"); ?> <!--Asynchronously Return User Names--> <script> $(document).ready(function(){ function search(){ var textboxvalue = $('input[name=search]').val(); $.ajax( { type: "GET", url: 'search.php', data: {Search: textboxvalue}, success: function(result) { $("#results").html(result); } }); }; </script> </head> <body> <div id="header-wrapper"> <?php include_once("../INC/nav2.php"); ?> </div> <div id="content"> <h1 style="color: red; text-align: center;">Member Directory</h1> <form onsubmit="search()"> <label for="search">Search for User:</label> <input type="text" size="70px" id="search" name="search"> </form> <a href="index.php?do=">Show All Users</a>|<a href="index.php?do=ONLINE">Show All Online Users</a> <div id="results"> <!--Results will be returned HERE!--> </div>search.php <?php //testing if data is sent ok echo "<h1>Hello</h1><br>" . $_GET['search']; ?>This is the link I get after sending foo. http://www.family-li...php?&search=foo Is that mean it was sent, but I'm not processing it correctly? I'm new to the whole AJAX thing. |