PHP - Database Driven Calendar Problem
I am trying to write out a calendar style html table with data in each cell, and with a column on the left that shows the times.
Basically it should look like this when written out to the webpage: Time Mon Tues Wed Thur Fri Sat 8:00 data data2 9:30 data3 data4 10:00 data5 data6 11:00 data7 data8 The times on the left will vary each month, and the 'data' (these are actually fitness classes held each month) will appear on various days of the week. There is no need to toggle from one month to the next and such, it's just a listing of the current month to display the classes held on which days and at which times. Very easy to do statically in html, but a bit more challenging dynamically. Using MySQL, the table that holds the data looks like this: Code: [Select] schedule_id class_time class_title day_order 1 08:00 data 1 2 08:00 data2 3 3 09:30 data3 2 4 09:30 data4 4 5 10:00 data5 3 6 10:00 data6 5 7 11:00 data7 1 8 11:00 data8 3 The day_order field corresponds to the weekday - Mon is 1, Tues is 2, etc. My query looks like this: Code: [Select] SELECT schedule_id, class_time, class_title, day_orderFROM `class_schedule` order by class_time, day_order Here is the html/ php code to write it out: Code: [Select] <table border="0" cellpadding="2" cellspacing="0" width="625"> <tr> <td class="calheader">Time</td> <td class="calheader">Mon</td> <td class="calheader">Tue</td> <td class="calheader">Wed</td> <td class="calheader">Thu</td> <td class="calheader">Fri</td> <td class="calheader">Sat</td> <td class="calheader">Sun</td> </tr> <? $i=0; $first_time = ""; while($i<$num_rows){ $sid = mysql_result($sql,$i,"schedule_id"); $ctime = mysql_result($sql,$i,"class_time"); $cdate = mysql_result($sql,$i,"CURDATE()"); $strtime = date("h:i:s",$cdate.$ctime); $ctitle = stripslashes(mysql_result($sql,$i,"class_title")); $order = mysql_result($sql,$i,"day_order"); if ($ctime != $first_time){ if (isset($first_time)){ echo ""; } if ($first_time == ""){ echo "<tr>\n"; echo "<td class=\"timecell\">". $ctime ."</td>\n"; } $first_time = mysql_result($sql,$i,"class_time"); } $j = 1; while ($j<8 && $first_time != ""){ if ($order == $j){ $thetitle = $ctitle; } else { $thetitle = " "; } echo "<td class=\"calcell\">". $thetitle ."</td>\n"; $j++; } unset($first_time); if (!isset($first_time)) { echo "</tr>\n"; } $i++; } unset($ctitle); unset($thetitle); unset($weekday); unset($sid); unset($clink); unset($order); mysql_close(); The above code sort of works, but the trouble I am having is that it is creating a new table row for each class, even if they occur at the same time slot. It should be putting them on the same row, to the right of the time slot across the days of the week. If anyone could assist, that would be wonderful - I am really stuck with this... Thanks Similar TutorialsHello, I am making a small CMS and I having some trouble with making a dynamic menu. I am wondering for a few days how I should make this menu system. I have the follow MySQL table: Code: [Select] CREATE TABLE `pages` ( `id` int(4) unsigned NOT NULL AUTO_INCREMENT, `time` varchar(10) DEFAULT NULL, `lastby` varchar(2) DEFAULT NULL, `order_id` varchar(2) DEFAULT NULL, `text` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB; Now I would like to have a menu system as following that I make menu's in a menu table with a name and a menu ID and that I could place those pages as parent or as subparent. How could I manage to turn my theory into reality? Sorry for my bad english but i hope you would understand my query. How can i set 404 not found for database driven pages..? I am using header("HTTP/1.0 404 Not Found"); in my 404 error page and ErrorDocument 404 /404.html, whereas 404.html is my error page. i have an URL http://www.example.com/folder/my-test-for-url-95/ which is opening correctly because it has existence on database. but when i am opening http://www.example.com/folder/my-test-for-url-951/ which has existence on database is also opening without any information but i want here a 404 not found page. How can i do so. Thanks Hi all, I am wondering what the best way to do this is... Take GoDaddy for example, if your domain is about to expire you will get an automatic email. I am wanting to do something similar, If someone orders a Soap Dispenser, I want to send an email (if they accept to receiving emails on the order) each month asking/reminding them to top up on soap. I have been reading but cant find anything adequate, I have seen something about Cron Jobs, but never heard of this before, please could you point me in the right direction. Thanks in advance. Peter Whats the best way to make a database driven menu ? Right now I have a db that looks like id | boats | Inshore id | boats | Offshore id | boats | Bay Boats and so on I'm think of going to database 1 id-1 | boats database 2 id | 1 | inshore or would a multideminsional array work best. My goal is to have the short term format be Boats Inshore Offshore Bay Boats and in the long term a format whose style I can change later, I wanted to get ideas from people in the know and have done this before. Thanks in advance I am trying to create a calendar of Events for my company's website. When I search for this type of calendar, I can find code that runs the calendar from one Events table. However, we could have an Event that has multiple performances. (For example, Lily Tomlin could be performing at the Atwood Concert Hall in Anchorage on 09/09/11 and at the Vagabond Blues in Palmer on 09/10/11.) So we have two tables to draw the information from: Events and Performance I can successfully create a MySQL query (see below) with PHP coding that will make a listing (as demostrated on our website http://www.centertix.net/). Code: [Select] "SELECT Events.PublishDate, Events.EventOnSaleDate, Events.BldgContractDate, Events.SetUpComplete, Events.EventTitle, Performance.PerfID, Performance.startDateTime, Performance.endDateTime, Performance.PerfType, venues.VenueName, venues.VenueCode FROM (Performance RIGHT JOIN Events ON Performance.EventID = Events.EventID) LEFT JOIN venues ON Performance.VenueCode = venues.VenueCode WHERE Events.BldgContractDate Is Not Null AND Events.SetUpComplete Is Not Null AND Performance.PerfType='Public Event'"However, I'm not advanced enough to create the if-clause or while-loop to check to see if the Performance.startDate = the calendar's date and then place the info into the appropriate calendar grid box. I think have determined where it should be place in my PHP code, but need help getting the calendar to work. Here's the code where I think it should go: Code: [Select] for($list_day = 1; $list_day <= $days_in_month; $list_day++): if(($list_day == date("j",mktime(0,0,0,$this->month))) && (date("F") == date("F",mktime(0,0,0,$this->month))) && (date("Y") == date("Y",mktime(0,0,0,$this->month,$list_day,$this->year)))) { $this->calendar.= '<td class="'. $this->style .'-current-day">'; } else { if(($running_day == "0") || ($running_day == "6")) { $this->calendar.= '<td class="'. $this->style .'-weekend-day">'; } else { $this->calendar.= '<td class="'. $this->style .'-day">'; } } /* add in the day number */ $this->calendar.= '<div class="'. $this->style .'-day-number">'.$list_day.'</div>'; /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/ $this->calendar.= '<div class="'. $this->style .'-text"><a href="">PERFORMANCE INFO</a></div>'. "\n"; /** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF NO MATCHES FOUND, PRINT NOTHING !! **/ $this->calendar.= str_repeat('<p> </p>',2); $this->calendar.= '</td>'; if($running_day == 6): $this->calendar.= '</tr>'; if(($day_counter+1) != $days_in_month): $this->calendar.= '<tr class="'. $this->style .'-row">'; endif; $running_day = -1; $days_in_this_week = 0; endif; $days_in_this_week++; $running_day++; $day_counter++; endfor; Please help me plug the calendar in with the appropriate events! If you would like to see how far I have gotten, you can check out this link: http://www.myalaskacenter.com/calendars/calendarSample2.php Good day! I created a webpages and i have a login page consist of Username and Department. And i encountered problem in adding event in my calendar. This is the flow of my webpage: First I have a separate table for the user and calendar. In my user table it has a Username, Department, and Permission. In the permission I put True or False, only one user i put True because i want that user is the one who permitted to add event or if she is login the add event link appear, but if other login the add even0t did not appear. This is my code in login: <?php session_start(); session_regenerate_id(); if($_SESSION['loggedin']){ //the user is already logged in, lets redirect them to the other page header("Location:company.php"); } //require_once 'conn.php'; $db_name="dspi"; mysql_connect("localhost", "root", "") or die("Cannot connect to server"); mysql_select_db("$db_name")or die("Cannot select DB"); $department = mysql_real_escape_string($_POST['department']); $username = mysql_real_escape_string($_POST['username']); $sql=mysql_query("SELECT `Department`, `Username` FROM `tbllogin` WHERE `Department` = '{$department}' AND Username = '{$username}'") or die(mysql_error()); $ct = mysql_num_rows($sql); if($ct == 1) { // im guessing this means that the user is valid. $_SESSION['loggedin'] = true; // now that the user is valid we change the session value. $row = mysql_fetch_assoc($sql); $_SESSION['username'] = $row['Username'] ; $_SESSION['department'] = $row['Department']; $Departments=array('Accounting', 'Engineering', 'Finishing_Goods', 'HRAD', 'MIS', 'Packaging_and_Design', 'Production', 'Purchasing_Logistic', 'QA_and_Technical', 'Supply_Chain'); if (in_array($row['Department'], $Departments)){ header ('Location:company.php'); }else{ echo "Incorrect Username or Department"; header ('Location:index.php'); } } ?> and this is my code in calendar page: <?php session_start(); $host = "localhost"; $username = ""; $password = ""; $dbCnx = @mysql_connect($host, $username, $password) or die('Could not Connect to the database'); $dbName = 'dspi'; mysql_select_db($dbName); ?> <html> <body> <script> function goLastMonth(month, year){ // If the month is January, decrement the year if(month == 1){ --year; month = 13; } document.location.href = '<?=$_SERVER['PHP_SELF'];?>?month='+(month-1)+'&year='+year; } //next function function goNextMonth(month, year){ // If the month is December, increment the year if(month == 12){ ++year; month = 0; } document.location.href = '<?=$_SERVER['PHP_SELF'];?>?month='+(month+1)+'&year='+year; } function remChars(txtControl, txtCount, intMaxLength) { if(txtControl.value.length > intMaxLength) txtControl.value = txtControl.value.substring(0, (intMaxLength-1)); else txtCount.value = intMaxLength - txtControl.value.length; } function checkFilled() { var filled = 0 var x = document.form1.calName.value; //x = x.replace(/^\s+/,""); // strip leading spaces if (x.length > 0) {filled ++} var y = document.form1.calDesc.value; //y = y.replace(/^s+/,""); // strip leading spaces if (y.length > 0) {filled ++} if (filled == 2) { document.getElementById("Submit").disabled = false; } else {document.getElementById("Submit").disabled = true} // in case a field is filled then erased } </script> <?php //$todaysDate = date("n/j/Y"); //echo $todaysDate; // Get values from query string $day = (isset($_GET["day"])) ? $_GET['day'] : ""; $month = (isset($_GET["month"])) ? $_GET['month'] : ""; $year = (isset($_GET["year"])) ? $_GET['year'] : ""; //comparaters for today's date //$todaysDate = date("n/j/Y"); //$sel = (isset($_GET["sel"])) ? $_GET['sel'] : ""; //$what = (isset($_GET["what"])) ? $_GET['what'] : ""; //$day = (!isset($day)) ? $day = date("j") : $day = ""; if(empty($day)){ $day = date("j"); } if(empty($month)){ $month = date("n"); } if(empty($year)){ $year = date("Y"); } //set up vars for calendar etc $currentTimeStamp = strtotime("$year-$month-$day"); $monthName = date("F", $currentTimeStamp); $numDays = date("t", $currentTimeStamp); $counter = 0; //$numEventsThisMonth = 0; //$hasEvent = false; //$todaysEvents = ""; //run a selec statement to hi-light the days function hiLightEvt($eMonth,$eDay,$eYear){ //$tDayName = date("l"); $todaysDate = date("n/j/Y"); $dateToCompare = $eMonth . '/' . $eDay . '/' . $eYear; if($todaysDate == $dateToCompare){ //$aClass = '<span>' . $tDayName . '</span>'; $aClass='class="today"'; }else{ //$dateToCompare = $eMonth . '/' . $eDay . '/' . $eYear; //echo $todaysDate; //return; $sql="select count(calDate) as eCount from calTbl where calDate = '" . $eMonth . '/' . $eDay . '/' . $eYear . "'"; //echo $sql; //return; $result = mysql_query($sql); while($row= mysql_fetch_array($result)){ if($row['eCount'] >=1){ $aClass = 'class="event"'; }elseif($row['eCount'] ==0){ $aClass ='class="normal"'; } } } return $aClass; } ?> <div id="Calendar_Event"> <table width="350" cellpadding="0" cellspacing="0"> <tr> <td width="50" colspan="1"> <input type="button" value=" < " onClick="goLastMonth(<?php echo $month . ", " . $year; ?>);"> </td> <td width="250" colspan="5"> <span class="title" style="color:#FFFFFF"><?php echo $monthName . " " . $year; ?></span><br> </td> <td width="50" colspan="1" align="right"> <input type="button" value=" > " onClick="goNextMonth(<?php echo $month . ", " . $year; ?>);"> </td> </tr> <tr> <th>M</td> <th>T</td> <th>W</td> <th>T</td> <th>F</td> <th>S</td> <th>S</td> </tr> <tr> <?php for($i = 1; $i < $numDays+1; $i++, $counter++){ $dateToCompare = $month . '/' . $i . '/' . $year; $timeStamp = strtotime("$year-$month-$i"); //echo $timeStamp . '<br/>'; if($i == 1){ // Workout when the first day of the month is $firstDay = date("N", $timeStamp); for($j = 1; $j < $firstDay; $j++, $counter++){ echo "<td> </td>"; } } if($counter % 7 == 0 ){ ?> </tr><tr> <?php } ?> <!--right here--><td width="50" <?=hiLightEvt($month,$i,$year);?>><a href="<?=$_SERVER['PHP_SELF'] . '?month='. $month . '&day=' . $i . '&year=' . $year;?>&v=1"><?=$i;?></a></td> <?php } ?> </table> </div> <div id="New_Event"> <?php if(isset($_GET['v'])){ if(isset($_POST['Submit'])){ $sql="insert into calTbl(calName,calDesc,calDate,calStamp) values('" . $_POST['calName'] ."','" . $_POST['calDesc'] . "','" . $_POST['calDate'] . "',now())"; mysql_query($sql); } $sql="select calName,calDesc, DATE_FORMAT(calStamp, '%a %b %e %Y') as calStamp from calTbl where calDate = '" . $month . '/' . $day . '/' . $year . "'"; //echo $sql; //return; $result = mysql_query($sql); $numRows = mysql_num_rows($result); $check=mysql_query("SELECT * FROM tbllogin WHERE Username='xxx' AND Department='HRAD' AND Permission='True'"); mysql_fetch_array($check); if($check['Username']=='xxx' && $check['Department']=='HRAD'){ $_SESSION['isallowed'] = $check['Permission']; //if (mysql_num_rows($check)>0){ ?> <a href="<?=$_SERVER['PHP_SELF'];?>?month=<?=$_GET['month'] . '&day=' . $_GET['day'] . '&year=' . $_GET['year'];?>&v=1&f=true">Add Even</a><a href="<?=$_SERVER['PHP_SELF'];?>?month=<?=$_GET['month'] . '&day=' . $_GET['day'] . '&year=' . $_GET['year'];?>&v=1&f=true">t</a><?php }else{ echo 'You cannot Add New Event'; }?> </div> <div id="Cal_Event"> <?php if(isset($_GET['f'])){ include 'calform.php'; } if($numRows == 0 ){ echo ''; }else{ //echo '<ul>'; echo '<h3>Event Listed</h3>'; while($row = mysql_fetch_array($result)){ ?> <h5><?=$row['calName'];?></h5> <?=$row['calDesc'];?><br/> Listed On: <?=$row['calStamp'];?> <?php } } } ?> </div> </body> </html> In that code when the user log is xxx and when she click a date she want to add event the appear is "You cannot Add Event". I hope somebody can help me.. Thank you in advance... my problem is if my local date is february 1 or march 30... if i press previous month i cant see the month of february, but if i press the change the local date to february 2 or march 29 i can see the month of february in my event calendar... what should i do to see the month of february even i set the local date in february 1 or march 30.... heres the code Code: [Select] if (isset($_GET['day'])){ $day = $_GET['day']; } else { $day = date("j"); } if(isset($_GET['month'])){ $month = $_GET['month']; } else { $month = date("n"); } if(isset($_GET['year'])){ $year = $_GET['year']; }else{ $year = date("Y"); } $currentTimeStamp = strtotime( "$day-$month-$year"); $monthName = date("F", $currentTimeStamp); $numDays = date("t", $currentTimeStamp); I currently have an HTML form where the options for a certain drop-down menu are hard-coded. Instead, I want to use PHP to... 1. Look up the values in a column (cities) in a MySQL table (locations) 2. Make those values the only options in the dropdown menu. Any ideas how I would do this? This is what I have so far. <label for="city">What is your destination city?</label> <select class="form-control" id="city" name="city"> <?php //connect to the database $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); //grab the city names from the MySQL table $query = "SELECT cities FROM locations"; $res = mysqli_query($dbc, $query); while ($data = mysqli_fetch_assoc($res)) { echo '<option value="'.$data['cities'].'">'.$data['cities'].'</option>'; } //close the db connection mysqli_close($dbc); ?> </select> Hey folks! a two-part problem he PART 1: here's a weird problem i bumped into today. when i leave OUT the 'varTable' section (see the class designations), it generates a table (allbeit messed up for reasons that i'll get into in part 2). but when i put 'varTable' back in, it generates the first array output just fine, but nothing shows for the table. (i need the first to be able to display the array) why does that happen? PART 2: when the table DOES generate, it gives a lot of errors and $i counts up to 7! whaaaaat!? thanks in advance for your help. this has me stumped. i've tried resetting the array, different variable names...nothing worked. i also included the array output at the very bottom. seems like a lot of extra data in there to me...and the [ 0 ] is printing oddly here (spaces prevent odd formatting...). WR! DATABASE TABLE: | id | item | cost | use | -------------------------------- | 0 | basket | 35 | 1 | | 1 | bicycle | 165 | 1 | | 2 | glass | 5 | 1 | | 3 | running shoe | 156 | 1 | | 4 | silver | 300 | 1 | PHP CODE: Code: [Select] <?php include("constants.php"); <?php $connexion = mysql_connect(DB_SERVER, DB_USER, DB_PASS); if(!$connexion) { die("Database Connection Failed: ".mysql_error()); } $selectDB = mysql_select_db("DB_CHOICE", $connexion); if(!$selectDB) { die("Database Selection Failed: ".mysql_error()); } $query = "SELECT * "; $query .= "FROM basic_table"; $results = mysql_query($query, $connexion); if(!$results) { die("Database Query Failed: ".mysql_error()); } ?> <div> <pre class="varTable"> <?php while($checkTable = mysql_fetch_array($results)) { print_r($checkTable); } ?> </pre> </div> <br><br> <div id='codeBlock'> <table class='phpTable' width='500' cellpadding="10"> <?php // generate table header row while ($tableRow = mysql_fetch_array($results)) { echo "<tr>"; for($i=0; $i<count($tableRow); $i++) { echo "<td>" . $tableRow[$i] . "</td>"; } echo "</tr>\n"; } ?> </table> ARRAY OUPUT: Code: [Select] Array ( [0] => 1 [id] => 1 [1] => basket [item] => basket [2] => 35 [cost] => 35 [3] => 1 [usable] => 1 ) Array ( [0] => 2 [id] => 2 [1] => bicycle [item] => bicycle [2] => 165 [cost] => 165 [3] => 1 [usable] => 1 ) Array ( [0] => 3 [id] => 3 [1] => glass [item] => glass [2] => 5 [cost] => 5 [3] => 1 [usable] => 1 ) Array ( [0] => 4 [id] => 4 [1] => running shoe [item] => running shoe [2] => 14 [cost] => 14 [3] => 1 [usable] => 1 ) Array ( [0] => 5 [id] => 5 [1] => silver [item] => silver [2] => 300 [cost] => 300 [3] => 1 [usable] => 1 ) This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=351877.0 Hello all; I have a client that has a members area. He asked me to password protect it, which I did simply by assigning one static password. Now he wants a full username/login system where the member can set their own password, which I have never done before. I assume I'd just set up a Table with three fields, (one for name, one for password, one for the type of access they have) then check against it for access, but experience has taught me that whenever something seems simple, it's actually very complex. Do any of you know of any good premade templates for this kind of thing? Ideally it'd be session-based (obviously). I found one system he http://frozenade.wordpress.com/2007/11/24/how-to-create-login-page-in-php-and-mysql-with-session/ but it's several years old, and the misspellings in the comments tend to scare me away a bit. Thanks for any help you might be able to provide. Hi, if someone could assist me, it would be much appreciated. I have a database website. I generated it using AppGini. Unfortunatly, they haven't answered my emails. What I'm trying to do is change my database to not dynamically load the selected record, but to instead load the direct URL to the record. (Here is the website address: http://2g2egkxd3.site.aplus.net/updates/bad_view.php) If you hover above the record, you will see the full URL for that record. Example: http://2g2egkxd3.site.aplus.net/updates/bad_view.php?SelectedID=Buck%20Allen But when you click it, it doesn't load that URL into the browser. I'm guessing it dynamically loads it into the page. The reason I'm trying to do this is because I want to have a social/comment system for each record/prospect and it won't work if the record is dynamically loaded. Hi all Good morning / night / afternoon I have a duplication problem when I need to print my records in PHP First of all let's see the database table As you can see the duplication happened duo to the approvers that mean if there is only one approver there will be no duplication For example when I want to pint request number 1 it will print 1 - Cris - Hadi 1 - Cris - Jack but I want it to be like this 1 - Cris - Hadi,Jack and thank you for your time Hey, i have a script in my game that picks up the output rate of a unit which if there is more than one unit it devides, i have 3 teams and the script picks up team 1 and 2, but any units in team 3 the rate shows 0? IE HEAVY SOLDIER 100% but with the 3rd team its always showing 0% Code: [Select] <font face="Verdana" color="#000000" size="2"><b>Output Rate</b></font></td></tr>'; $sql = "SELECT id,name FROM units WHERE class={$row[0]} AND visible=1"; $r2 = mysql_query($sql); while ($row2 = mysql_fetch_row($r2)) { echo '<tr><td align="center">'.$row2[1].'</td><td align="center"><input text="text" size="5" style="'.$boxStyle.'" name="a'.$row2[0].'" value='.getRate($userid,$row2[0]).'>%</td></tr>'; } echo '<tr><td colspan="2" align="center"><input type="submit" value="Set Rates for '.$row[1].'"></td></tr>'; echo '</table></form>'; } echo '</center>'; DB's Code: [Select] FOR UNITS. id name toground toair hp class evolvesto style cost visible 6 Mulanix 10 10 200 3 0 1 20 1 5 Numani 5 5 100 3 6 1 10 1 any help would be great it's annoying me and i can't solve it. Hi, For school, I need to build a site and this site has to have a few applications. One of the applications, I have to make is to make a script that makes it possible to upload a file and it has to put this file in a online database. Now, I'm just trying to put it in a local database. My code doesn't give an error, but it doesn't work either. The file doesn't get into the database. I can't figure out why. I hope you can help me? Thanks in advance! Lize Google Chrome Developer Tool causes an error when I run the following and there are not any records. I keep getting errors when I try to change it.
<?php $host = 'localhost'; $user = 'root'; $pass = ''; $database = 'ecommerce'; $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false ); $keyword = $_GET['keyword']; $dbo = new PDO("mysql:host=$host;dbname=$database", $user, $pass, $options); $q1 = "SELECT * FROM products INNER JOIN keywords on keywords.keywordID = products.KeywordID and keywords.KeyWord1 = \"$keyword\" "; $counter = 10; $counter1 = 0; foreach ($dbo->query($q1) as $row) {
hi, i was having difficulty and i'm quite confused how to insert these values to the database before it will become as it is, based on this article: http://roshanbh.com.np/2008/01/populate-triple-drop-down-list-change-options-value-from-database-using-ajax-and-php.html what i did was putting/saving the values directly in the database (mysql). but now i want those values to be coming from the user's input:the country,state and city so the system will just get those values, store it to the database with the fields of each table having the same content like that from article above..i really need some help here.. Hello everybody, I have a script that allows a user to set themselves a target and a script that allows them to edit the target if they decide to. Now everything works as it should until the data from the form (on the edit target page) should be updated in the database. I require that the user must update at least one field. For example they may want to extend the completion date so I would only want to update the completion date field in the database and the fields the user left blank should not be updated in the database. The problem I am having is regardless of if the user enter a value into the field it updates the database so if the user leaves a field blank it updates the database will a blank value. Here is my code: //If the user clicks the update button on a WEIGHT LOSS target run the following code to update the database if(isset($_POST['target_weight_loss_update'])){ $target_weight_loss_update = $_POST['target_weight_loss_update']; $weight_loss_complete_update = $_POST['weight_loss_complete_update']; $weight_loss_comment_update = $_POST['weight_loss_comment_update']; $weight_loss_user_id_update = $_POST['weight_loss_user_id_update']; //Check that at least one value has been entered into the form if(empty($target_weight_loss_update) && empty($weight_loss_complete_update) && empty($weight_loss_comment_update)){ $error_msg = 'Please enter at least one value to update your '.$target_type.' target'; } //Check to see what variables have values in them so we know what fields to update in datebase //If the user has entered a value for their TARGET WEIGHT LOSS update that value in the database if(isset($target_weight_loss_update) || !empty($target_weight_loss_update)){ $target_weight_loss_update_sql = mysql_query("UPDATE user_targets SET target_weight='$target_weight_loss_update' WHERE id='$target_id' LIMIT 1") or die (mysql_error()); //Check that the update was successful if($target_weight_loss_update_sql){ $error_msg = 'Target '.$target_type.' updated successfully'; } else { $error_msg = 'Could not update target. Please try again.'; } } //If the user has entered a value for their TARTGET WEIGHT LOSS DATE update that value in the database if(isset($weight_loss_complete_update) || !empty($weight_loss_complete_update)){ $weight_loss_completion_date_sql = mysql_query("UPDATE user_targets SET target_date='$weight_loss_complete_update' WHERE id='$target_id' LIMIT 1") or die (mysql_error()); //Check that the update was successful if($weight_loss_completion_date_sql){ $error_msg = 'Target '.$target_type.' updated successfully'; } else { $error_msg = 'Could not update target. Please try again.'; } } //If the user has entered a value for their TARGET WEIGHT LOSS COMMENT update that value in the database if(isset($weight_loss_comment_update) || !empty($weight_loss_comment_update)){ $weight_loss_comment_update_sql = mysql_query("UPDATE user_targets SET extra_info='$weight_loss_comment_update' WHERE id='$target_id' LIMIT 1") or die (mysql_error()); //Check that the update was successful if($weight_loss_comment_update_sql){ $error_msg = 'Target '.$target_type.' updated successfully'; } else { $error_msg = 'Could not update target. Please try again.'; } } } So the question I ask is how can I stop entering blank values into the database and only update the information the user enters into the form? Also I was thinking of having one mysql query at the end and using the IF statements to build the query. Thoughts? Thanks for any advice. |