PHP - Determining An Average Date
Could someone please advise the best way to determine the average of a DATE field in a SELECT query?
Similar TutorialsHere is the scenario: Members of my group turn in/donate uniform items they don't need to me...stuff that can be passed on to other members that need it. I post these items onto our website. A member, who needs an item, visits the site, and picks the items that they need. After selecting everything they need, they provide only their name and maybe some comments, and submit the request. An e-mail is generated and sent to me, listing out all the items the member has requested. I gather the items, and bring them to the member at the next meeting. My original plans were to use a shopping cart type script; however, I have since found out that I am not allowed a MySQL database on the server I am using! I've seen some shopping carts out there that use php & excel, not requiring a database, but they are all trial, and have limitations of only like 10 items. Does anyone have any ideas on the best way to handle this scenario? I was thinking an html form of some type with check boxes next to each item; then, upon pressing submit, a php script sends me an e-mail listing the boxes they have checked. Only problem with that is, having to update the php script each time I add/delete an item and it's checkbox (would have to add/delete that checkbox's name to the script each time...correct?). Thanks for any suggestions, - Jason With this code I can determine the fieldname and the value. They are $col_key and $col_value respectively: Code: [Select] $sql = "SELECT * FROM $tbl "; $result = mysql_query($sql) while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { if ($row == 1) { foreach ($line as $col_key => $col_value) { But how do I determine the field TYPE (i.e. varchar, text, date etc)? Hey, I have a search feature that searches for words in my database. I am currently storing all searches that users make in a table called `search`. I need to list the top 10 words that are searched for the most, excluding common words like "the, and, or, etc". Because the searches users make are stored into a table, it should be fairly easy. Could anyone give an example of how to do this? Here's how my sql table looks: table name: search columns: id (autoincrement) phrase date resultsfound ip Hi Guys Quick question. I am just starting an application that enables users to upload files - specifically image files. As one of the validation/security steps I want to run a check on file type and file size. As far as i can see you do this one of two ways: 1) using the $_FILES array - i.e. $_FILES[name][type] and $_FILES[name][size] or 2) using the getimagesize() function. What i want to know is whether one of these methods is preferable for security or do they both suffer the same inherent flaws - because lots of post online seem to suggest filetype can be faked. advice would be appreciated I have a PHP script that downloads a file from a remote server but in order to download the correct file it has to subtract 1 day of the week. It used to work quite some time ago so I dont know what is going on now. The section of the script goes like this....
$days = array("sun","mon","tue","wed","thu","fri","sat"); $today = date("w"); $yesterday = $days[$today - 1];Then it joins the 3 letter version of the day of week with a file name to grab the correct file download. $yesterday is not returning the correct value instead I am getting an error... # ./update.php PHP Notice: Undefined offset: -1 in /root/fcc/work/update.php on line 6 fetching l_am_.zip ncftpget: server said: l_am_.zip: No such file or directory. PHP Warning: unlink(counts): No such file or directory in /root/fcc/work/update.php on line 23 data set empty nothing to process Sun, 01 February, 2015 6:29:06 PMSo in the above error I can see that $yesterday is "Undefined offset" and because of that the file it tries to download is incorrect, it should have tried to download l_am_sat.zip and it left out the 3 letter date code. Edited by chadrt, 01 February 2015 - 09:48 PM. I am trying to write a script that runs through a CSV file and inserts unique values in a mysql database and spits the duplicate out into a new CSV. I can find the duplicates when I load it into an array, but when I insert them into a MySQL database, I cannot determine if they are duplicates. If I use INSERT IGNORE, it will run the whole file, and reject the duplicates. This is fine, except I need to create a file of the duplicate entries. What is the best way to determine if the insert attempt was rejected? I could do a select to see if the row is there, spit it out...insert if not, but I was thinking there should be a way for MySQL to talk back to me to cut the queries in half... Any ideas? Thanks I'm using a time stamp where I'm getting the date and time from the database server rather than using a unix time stamp. Because I'm in a different time zone as the server, my time was always off by 1 hour. I fixed that problem by writing some code to adjust the hour of the time and the date depending on what time it was. It was working fine until a few weeks ago when I had to adjust my clock for daylight savings time... now the time is off by 2 hours because of that. Well, I fixed that and now it's working fine again. My question is does anyone know of a way to automatically determine whether or not I should be in daylight savings time or not so I can just use an if/else statement to keep the time adjusted properly rather than having to do it manually every time the time changes? Basically, I would like to do it something like the following: Code: [Select] <?php if ($daylightsavings = "y") { (adjust time/date for 1 hour difference); } else { (adjust time/date for 2 hour difference); } ?> Anyone have any ideas? When a user logs on, I authenticate them with a session. How do I use php to determine the time until the session will expire? I realize I could go into the ini file but is there a php code that can query this info and echo it back? Hi, I found a tutorial online for a form which used PHP/MySQL and JQuery to submit data. I am making some modifications and the form no-longer submits the data. The problem I have is no errors display so I am not sure where the problem lies. I need to be able to display a success or failure message on the form itself, but this is either not there or not working. The code is below. Code: [Select] <form id="ContactForm" action=""> <p> <label>First Name</label> <input id="FirstName" name="FirstName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span> </p> <p> <label>Last Name</label> <input id="LastName" name="LastName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span> </p> <p> <label>User Name</label> <input id="UserName" name="UserName" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span> </p> <p> <label>Email</label> <input id="email" name="email" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> <span class="error" style="display:none;"></span> </p> <p> <label>Website<span>(optional)</span></label> <input id="website" name="website" class="inplaceError" maxlength="120" type="text" autocomplete="off"/> </p> <p> <label>Your message<br /> <span>300 characters allowed</span></label> <textarea id="message" name="message" class="inplaceError" cols="6" rows="5" autocomplete="off"></textarea> <span class="error" style="display:none;"></span> </p> <p class="submit"> <input id="send" type="button" value="Submit"/> <span id="loader" class="loader" style="display:none;"></span> <span id="success_message" class="success"></span> </p> <input id="newcontact" name="newcontact" type="hidden" value="1"></input> </form> <?php require_once("config.php"); /* Configuration File */ class DB{ private $link; public function __construct(){ $this->link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME); if (mysqli_connect_errno()) exit(); } public function __destruct() { mysqli_close($this->link); } public function dbNewMessage($email,$FirstName,$LastName,$website,$message){ $email = mysqli_real_escape_string($this->link,$email); $FirstName = mysqli_real_escape_string($this->link,$FirstName); $LastName = mysqli_real_escape_string($this->link,$LastName); $UserName = mysqli_real_escape_string($this->link,$UserName); $website = mysqli_real_escape_string($this->link,$website); $message = mysqli_real_escape_string($this->link,$message); mysqli_autocommit($this->link,FALSE); $query = "INSERT INTO contact_me(pk_contact,FirstName,LastName,UserName,email,website,message) VALUES('NULL','$FirstName','$LastName','$UserName','$email','$website','$message')"; mysqli_query($this->link,$query); if(mysqli_errno($this->link)) return -1; else{ mysqli_commit($this->link); return 1; } } }; ?> <?php require_once("db.php"); /* Database Class */ require_once('utils/is_email.php'); /* Email Validation Script */ /* Handle Ajax Request */ if(isset($_POST['newcontact'])){ $contact = new Contact(); unset($contact); } else{ header('Location: /'); } /* Class Contact */ class Contact{ private $db; /* the database obj */ private $errors = array(); /* holds error messages */ private $num_errors; /* number of errors in submitted form */ public function __construct(){ $this->db = new DB(); if(isset($_POST['newcontact'])) $this->processNewMessage(); else header("Location: /"); } public function processNewMessage(){ $email = $_POST['email']; $FirstName = $_POST['FirstName']; $LastName = $_POST['LastName']; $UserName = $_POST['UserName']; $website = $_POST['website']; $message = $_POST['message']; /* Server Side Data Validation */ /* Email Validation */ if(!$email || mb_strlen($email = trim($email)) == 0) $this->setError('email','required field'); else{ if(!is_email($email)) $this->setError('email', 'invalid email'); else if(mb_strlen($email) > 120) $this->setError('email', 'too long! 120'); } /* FirstName Validation */ if(!$FirstName || mb_strlen($FirstName = trim($FirstName)) == 0) $this->setError('FirstName', 'required field'); else if(mb_strlen(trim($FirstName)) > 120) $this->setError('FirstName', 'too long! 120 characters'); /* LastName Validation */ if(!$LastName || mb_strlen($LastName = trim($LastName)) == 0) $this->setError('LastName', 'required field'); else if(mb_strlen(trim($LastName)) > 120) $this->setError('LastName', 'too long! 120 characters'); /* UserName Validation */ if(!$UserName || mb_strlen($UserName = trim($UserName)) == 0) $this->setError('UserName', 'required field'); else if(mb_strlen(trim($UserName)) > 120) $this->setError('UserName', 'too long! 120 characters'); /* Website Validation */ if(!mb_eregi("^[a-zA-Z0-9-#_.+!*'(),/&:;=?@]*$", $website)) $this->setError('website', 'invalid website'); elseif(mb_strlen(trim($website)) > 120) $this->setError('website', 'too long! 120 characters'); /* Message Validation */ $message = trim($message); if(!$message || mb_strlen($message = trim($message)) == 0) $this->setError('message','required field'); elseif(mb_strlen($message) > 300) $this->setError('message', 'too long! 300 characters'); /* Errors exist */ if($this->countErrors() > 0){ $json = array( 'result' => -1, 'errors' => array( array('name' => 'email' ,'value' => $this->error_value('email')), array('name' => 'FirstName' ,'value' => $this->error_value('FirstName')), array('name' => 'LastName' ,'value' => $this->error_value('LastName')), array('name' => 'UserName' ,'value' => $this->error_value('UserName')), array('name' => 'website' ,'value' => $this->error_value('website')), array('name' => 'message' ,'value' => $this->error_value('message')) ) ); $encoded = json_encode($json); echo $encoded; unset($encoded); } /* No errors, insert in db*/ else{ if(($ret = $this->db->dbNewMessage($email, $FirstName, $LastName,$UserName, $website, $message)) > 0){ $json = array('result' => 1); if(SEND_EMAIL) $this->sendEmail($email,$name,$website,$message); } else $json = array('result' => -2); /* something went wrong in database insertion */ $encoded = json_encode($json); echo $encoded; unset($encoded); } } public function sendEmail($email,$name,$website,$message){ /* Just format the email text the way you want ... */ $message_body = "Hi, ".$name."(".$email." - ".$website.") sent you a message from yoursite.com\n" ."email: ".$email."\n" ."message: "."\n" .$message; $headers = "From: ".EMAIL_FROM_NAME." <".EMAIL_FROM_ADDR.">"; return mail(EMAIL_TO,MESSAGE_SUBJECT,$message_body,$headers); } public function setError($field, $errmsg){ $this->errors[$field] = $errmsg; $this->num_errors = count($this->errors); } public function error_value($field){ if(array_key_exists($field,$this->errors)) return $this->errors[$field]; else return ''; } public function countErrors(){ return $this->num_errors; } }; ?> and the JQuery Code: [Select] $(document).ready(function() { contact.initEventHandlers(); }); var contact = { initEventHandlers : function() { /* clicking the submit form */ $('#send').bind('click',function(event){ $('#loader').show(); setTimeout('contact.ContactFormSubmit()',500); }); /* remove messages when user wants to correct (focus on the input) */ $('.inplaceError',$('#ContactForm')).bind('focus',function(){ var $this = $(this); var $error_elem = $this.next(); if($error_elem.length) $error_elem.fadeOut(function(){$(this).empty()}); $('#success_message').empty(); }); /* user presses enter - submits form */ $('#ContactForm input,#ContactForm textarea').keypress(function (e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { $("#send").click(); return false; } else return true; }); }, ContactFormSubmit : function() { $.ajax({ type : 'POST', url : 'php/contact.php?ts='+new Date().getTime(), dataType : 'json', data : $('#ContactForm').serialize(), success : function(data,textStatus){ //hide the ajax loader $('#loader').hide(); if(data.result == '1'){ //show success message $('#success_message').empty().html('Message sent'); //reset all form fields $('#ContactForm')[0].reset(); //envelope animation $('#envelope').stop().show().animate({'marginTop':'-175px','marginLeft':'-246px','width':'492px','height':'350px','opacity':'0'},function(){ $(this).css({'width':'246px','height':'175px','margin-left':'-123px','margin-top':'-88px','opacity':'1','display':'none'}); }); } else if(data.result == '-1'){ for(var i=0; i < data.errors.length; ++i ){ if(data.errors[i].value!='') $("#"+data.errors[i].name).next().html('<span>'+data.errors[i].value+'</span>').fadeIn(); } } }, error : function(data,textStatus){} }); } };
Sir, { "DiplomaFirstYear": { "2016-2017.1": 3.88, "2016-2017.2": 4, "2016-2017.3": 3.3 }, "DiplomaSecondYear": { "2016-2017.3": 4, "2017-2018.1": 3.88, "2017-2018.2": 3.94, "2017-2018.3": 3.3 }, "AdvancedDiploma": { "2017-2018.3": 4, "2018-2019.1": 3.74, "2018-2019.2": 3.62 }, "Bachelor": { "2018-2019.3": 3.15 } }
I can't remember the math to do this, but I use MySQL to calculate an average: 5 = 100% 0 = 0% I want to make a bar that shows an average (like a bar graph) so lets say I get 2.5 as one of my returned results, that means the bar should only be 50% long of the maximum width. Using calculations, how can I get the number 50 (the max width is 100% of a table cell)? If you had a function that calculated the average of a fixed quantity of numbers, what type of scope issues would you anticipate? Hi. Im trying to make a PHP code that will find the average number. What I want is, a lot of input fields where you can write a number in. Then my code should take these numbers and divide them with the amount of input fields that has been written in. So that some fields you don't have to write a number, and the code will still give you a correct average. My code so far: Code: [Select] <?php if (isset($_POST['calc'])) { $m=$_POST['mat']; $e=$_POST['da']; $s=$_POST['eng']; $f=$_POST['fys']; $h=$_POST['bio']; $p=$_POST['geo']; $ave=($m+$e+$s+$f+$h+$p)/; } ?> <a href="" onclick="return hs.htmlExpand(this, { headingText: 'Beregn dit Gennemsnit:' })"> <b>Beregn dit Gennemsnit: <?php echo $ave;?></b><br></br> </a> <div class="highslide-maincontent"> <form id="gennemsnit" name="form1" method="post" action=""> Matematik<input name="math" type="text" id="mat" size="3" maxlength="4" /><br /> Dansk<input name="eng" type="text" id="da" size="3" maxlength="4" /><br /> Engelsk<input name="sci" type="text" id="eng" size="3" maxlength="4" /><br /> Fysik<input name="fil" type="text" id="fys" size="3" maxlength="4" /><br /> Biologi<input name="he" type="text" id="bio" size="3" maxlength="4" /><br /> Geografi<input name="pe" type="text" id="geo" size="3" maxlength="4" /></td><br /> <input name="calc" type="submit" id="calc" value="Beregn"/><br /><br /> </form> What I need is the code of how to divide with the amount of input fields that has been written in. thanks for any help hi all! i have 2 tables: PRODUCTS id_prod, id_cat, date, prod_name CATEGORIES id_cat, cat_name My goal is obtain the average (day and month) of all products inserted by users in this format: category Hardwa avg daily 20, month 100 category Components: avg daily 2, month 15 and so on. PS: the 'date' field is unix timestamp (int 10). Can you help me? Hi,
I have a blog which records the amount of views on each article. I now want to be able to work out the average number of views per hour.
How can I work out the number of hours passed from a datetime format?
From there I can just do views divided by hours passed.
Thanks in advance!
Hi, I'm trying to get out the average of records stored in a mysql table This is the code im using right now Code: [Select] mysql_query("SELECT DATE(dato) , COUNT( dato ) AS counted FROM dekodere GROUP BY date(dato)", $link); $ave = mysql_num_rows($ave); This is getting out the average, but i need to exclude weekends because there is not stored anything during the weekend so it's making the average go off.. any tips? Hi, Firstly, these are my tables: CLASS class_id class_name 1 Donkeys 2 Monkeys 4 Classic 9 Humans COURSES class_id courses_number 9 6 9 2 1 3 2 2 I would like to print average course_number for each class_name. So for class_name Donkeys would have average course_number 3. And for clasS_name Humans, average course_number is 4. Do you get my point? Nice forum here. I know nothing about PHP and need some help. Here is the deal. Members on a forum will be rating products. There will be 4 (this number could change) fields where they will select a number from a drop down menu to rate different characteristics of the product. I need to average those numbers for the overall rating. The code that outputs the individual numbers selected looks like this: {$data['record']['field_14']} 14 being one of the fields, and 15, etc. So what I need is code that takes multiple fields and outputs the average number. I appreciate any help! And please keep in mind I am not familiar with PHP coding, so if you could be as detailed as possible I would appreciate it. Thanks! I manage to display data using below query that will show value for each month. How to calculate average value starting july onwards(based on user selection).
Let say the value for element 'A' are Jul=80, Aug= 80, Sep=90. If user select Aug then the average is 80 and if user select Sep then the average is 83.
Query:
$sql2 = "Select element, SUM(CASE WHEN Month = 'Jan' THEN total ELSE 0 END ) AS Jan, SUM(CASE WHEN Month = 'Feb' THEN total ELSE 0 END ) AS Feb, SUM(CASE WHEN Month = 'Mac' THEN total ELSE 0 END ) AS Mac, SUM(CASE WHEN Month = 'Apr' THEN total ELSE 0 END ) AS Apr, SUM(CASE WHEN Month = 'May' THEN total ELSE 0 END ) AS May, SUM(CASE WHEN Month = 'Jun' THEN total ELSE 0 END ) AS Jun, SUM(CASE WHEN Month = 'Jul' THEN total ELSE 0 END ) AS Jul, SUM(CASE WHEN Month = 'Aug' THEN total ELSE 0 END ) AS Aug, SUM(CASE WHEN Month = 'Sep' THEN total ELSE 0 END ) AS Sep, SUM(CASE WHEN Month = 'Oct' THEN total ELSE 0 END ) AS Oct, SUM(CASE WHEN Month = 'Nov' THEN total ELSE 0 END ) AS Nov, SUM(CASE WHEN Month = 'Dec' THEN total ELSE 0 END ) AS Dis FROM tbl_ma GROUP BY element"; $rs2 = mysql_query($sql2); $getRec2 = mysql_fetch_assoc($rs2);Below is how print the data: <?php while ($row = mysql_fetch_assoc($rs2)) { ?> <tr> <td style="color:black;background-color:#f5efef"><div align="left"><?php echo $row['element']; ?></div></td> <?php if( $year != '2014' ){ ?> <?php if( 1 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Jan']; ?></div></td><?php endif; ?> <?php if( 2 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Feb']; ?></div></td><?php endif; ?> <?php if( 3 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Mac']; ?></div></td><?php endif; ?> <?php if( 4 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Apr']; ?></div></td><?php endif; ?> <?php if( 5 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['May']; ?></div></td><?php endif; ?> <?php if( 6 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Jun']; ?></div></td><?php endif; ?> <?php } ?> <?php if( 7 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Jul']; ?></div></td><?php endif; ?> <?php if( 8 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Aug']; ?></div></td><?php endif; ?> <?php if( 9 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Sep']; ?></div></td><?php endif; ?> <?php if( 10 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Oct']; ?></div></td><?php endif; ?> <?php if( 11 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Nov']; ?></div></td><?php endif; ?> <?php if( 12 <= $monthID ): ?><td><div align="center" style="color:black"><?php echo $row['Dis']; ?></div></td><?php endif; ?> <td><div align="center" style="color:black"><?php //echo average; ?></div></td> </tr> <?php } ?> I have a table of restaurant menu items called menu_items. This table has a float row(3,2) called price. I have a query that looks like this: $query = mysql_query("SELECT * FROM menu_items WHERE restaurant = '".$restaurantid."'"); How would I find the average of the price row from that query? Basically I want to find the average item price for a restaurants menu. |