PHP - Mysqli Query With Date Range Criteria
Hi,
I can I include a date range criteria to query with in the following code? The date field in the table (t_persons) is IncidentDate.
$criteria = array('FamilyName', 'FirstName', 'OtherNames', 'NRCNo', 'PassportNo', 'Gender', 'IncidenceCountryID', 'Status', 'OffenceKeyword', 'AgencyID', 'CountryID', 'IncidenceCountryID' ); $likes = ""; $url_criteria = ''; foreach ( $criteria AS $criterion ) { if ( ! empty($_POST[$criterion]) ) { $value = ($_POST[$criterion]); $likes .= " AND `$criterion` LIKE '%$value%'"; $url_criteria .= '&'.$criterion.'='.htmlentities($_POST[$criterion]); } elseif ( ! empty($_GET[$criterion]) ) { $value = mysql_real_escape_string($_GET[$criterion]); $likes .= " AND `$criterion` LIKE '%$value%'"; $url_criteria .= '&'.$criterion.'='.htmlentities($_GET[$criterion]); } //var_dump($likes); } $sql = "SELECT * FROM t_persons WHERE PersonID>0" . $likes . " ORDER BY PersonID DESC";Kind regards. Similar TutorialsHi i have the following code Quote
$sql= "SELECT * FROM income WHERE month(date) between '04' and '12' and year(date) between 2020 and 2020"; This obviously selects all the information from April 2020 to December 2020
How do i change this to add a date as well for example if i wanted to display all the information from April 6th 2020 to December 5th 2020 ?
I am currently working on a date range script and wondering if anybody think of an easier way to do this, doing up to next 8 weeks? This one starts on a Sunday. I also need to do one starting on a Monday (will figure that one later) $thisweek = date("Y-m-d"); $week = date('w', strtotime($thisweek)); $date = new DateTime($thisweek); $firstWeek = $date->modify("-".$week." day")->format("M d"); $endWeek = $date->modify("+6 day")->format("M d"); echo $firstWeek." - "; echo $endWeek; $nextweek = date(("Y-m-d"), strtotime("+7 Days")); $week1 = date('w', strtotime($nextweek)); $date1 = new DateTime($nextweek); $firstWeek1 = $date1->modify("-".$week1." day")->format("M d"); $endWeek1 = $date1->modify("+6 day")->format("M d"); echo $firstWeek1." - "; echo $endWeek1;
Why is this not working? Code: [Select] $result = mysql_query("SELECT * FROM contacts WHERE type = 'consumer' AND sent BETWEEN '".date("Y-m-d")."' AND '".date("Y-m-d", strtotime("-7 days"))."'") or die(mysql_error()); $numrows = mysql_num_rows($result); if($numrows < 0 ){ echo "No records found"; } The record that is stored in the sent column is like this "2011-11-03 14:42:12", so there is a record in there, but nothing is showing up. Can anyone see why? thanks in advance Hello, I'm very disapointed because I don't know how do it this. I'm explain. I have a database with one input date_arrival and second date_departure. Two dates are saved in SQL format : 2014-03-02. After my SQL request to select all dates in database I'd like to add dates between date_arrival and date_departure and for each line. For example I have date_arrival date_departure line 1 : 2014-02-01 2014-02-05 line 2 : 2014-02-10 2014-02-15 In fact at the end, I have to send the result like this (with JSON) : ["2014-02-01","2014-02-02","2014-02-03","2014-02-04","2014-02-05","2014-02-10","2014-02-11","2014-02-12","2014-02-13","2014-02-14","2014-02-15"] Can you give me some help to add intermediates values in an array ? Thx I am working on a report generation. Here I need to count the number of months involved in the selected date range. I need to apply the monthly charges accordingly. Example: If the user selects 25-08-2011 to 03-10-2011, it should return 3 as the number of months. Yes, the number of days are less than 60 but still the date range is spread across 3 months. Any solution.. Please. Girish Setup: Mysql table 1: acct#, client name, status(active/not active), Starting balance, ending balance Mysql table 2: acct#, invoice amount, invoice date, total how do i select all customers that are Active, and the starting balance != ending balance and then get the total for all invoices for that customer where the invoice date is between 2010-01-01 and 2010-03-01 Basically my out put needs to look like this. Customer name, Total of all invoices for customer john doe, $10,564.21 Susy Scott, $158.02 Bang Head, $837,294.85 Customer can have multiple invoices within the given date range. But I only need the total for all the invoices for each customer added up and echo'ed. Quickness is also a factor on the query and echo. Thank you for your valuable time. I'm trying to wrap my head around how i should go about doing this. I have two dates...2011-05-03 and 2011-05-08. I want to write a function that creates an array of the days that consist of that date range. So say something like Code: [Select] <?php $start = "2011-05-03"; $end = "2011-05-08"; function get_days($start, $end) { //code to get the days } echo get_days($start, $end); //hopefully produce something like... $day['1'] = "2011-05-03"; $day['2'] = "2011-05-04"; $day['3'] = "2011-05-05"; $day['4'] = "2011-05-06"; $day['5'] = "2011-05-07"; $day['6'] = "2011-05-08"; anybody know any idea how to do something like this? Pretty sure i'm going to need the mktime() function to account for ranges going across months and years. Hello, Im trying to work out some code. On my site between Thursday 12th July and Sunday 15th July between the hours of 22:00 and 23:00 I want to display some code. I've done this so far, but am having trouble. Anyone please help? $the_date = date("H:i:s"); $timesep = explode(":",$the_date); // $hour = $timesep[0]; if (($the_date > 2010-08-12 && < 2010-08-15) && ($hour >= 22) && ($hour <= 23)) { //Code } I'm trying to do the following PHP. I have written it in English if (today's date) => date1 AND <= date2 then {display image1} elseif (today's date) => date3 AND <= date4 then {display image2} else {display image 13} There are 24 fixed dates and 13 fixed images. I have tried using combinations of strtotime(), replacing the date value with variables, hard coding the dates within the program. I don't seem to be able to get any combination to work properly. I'm sure it's just a syntax error but I can't see it. When I've searched the web all the answers I've found relate to dates within databases but as I only have 24 dates it seems a bit of overkill. I would appreciate any pointers to the correct method I might be able to use. The dates need only a day and month as I would like this to repeat year after year. <?php $today = strtotime(date('d-m')); if (strtotime($today) >= strtotime('28-10') && strtotime($today) <= strtotime('24-11')) {echo "<div>image1</div>";} elseif (strtotime($today) >= strtotime('25-11') && strtotime($today) <= strtotime('22-12')) {echo "<div>image2</div>" ;} elseif (strtotime($today) >= strtotime('23-12') && strtotime($today) <= strtotime('24-02')) {echo "<div>image3</div>" ;} else {echo "<div>image13</div>";} ?> The result I get from this is image1 appears on the web page but I would expect image3 as today is 22-01 Thank you in advance. Andrew Hi all
This is a one I've spent DAYS on and can't figure out :-\ This is for a wedding venue and their pricing schedule is divided into low, medium, high and very high seasons. I.e. low season runs from 8 Jan 16 to 28 Feb 16, medium runs from 4 Mar 16 to 20 Mar 16, etc. The database for this is laid out as attached. I would like people to be able to enter their arrival and departure date and for it to be able to choose which seasons the date range falls under. I.e. If they stay 8 to 12 Jan, that's no problem to calculate and falls under LOW season. However, if they stay 27 Feb to 10 Mar, this falls under both LOW and MID seasons, with the majority of the stay in the MID season (which we'd price with but can use PHP to choose the 'highest' season from the array). I'm a bit stumped on this one so any help is hugely appreciated! I'm sure it's something quite simple that I'm missing. Attached Files Screen Shot 2015-01-10 at 16.58.17.png 146.3KB 0 downloads Hi. Im searching for a way to enter multiple records at once to mysql databased on a date range. Lets say i want to insert from date 2010-11-23 to date 2010-11-25 a textbox with some info and the outcome could look in database like below. ---------------------------------------------------------- | ID | date | name | amount | ----------------------------------------------------------- | 1 | 2010-11-23 | Jhon | 1 | | 2 | 2010-11-24 | Jhon | 1 | | 2 | 2010-11-25 | Jhon | 1 | ----------------------------------------------------------- The reason i need the insertion to be like this is because if quering by month and by user to see vacation days then vacations that start in one month and end in another month can be summed by one month. If its in one record then it will pop up in both months. Help is really welcome. I have the week date range displaying the week range from sunday - saturday
$current_dayname = date("0"); // return sunday monday tuesday etc. echo $date = date("Y-m-d",strtotime('last sunday')).'to'.date("Y-m-d",strtotime("next saturday")); Which outputs in the following format 2015-01-25to2015-01-31 However, when I press next or previous, the dates don't change. <?php $year = (isset($_GET['year'])) ? $_GET['year'] : date("Y"); $week = (isset($_GET['week'])) ? $_GET['week'] : date('W'); if($week > 52) { $year++; $week = 1; } elseif($week < 1) { $year--; $week = 52; } ?> <a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week == 52 ? 1 : 1 + $week).'&year='.($week == 52 ? 1 + $year : $year); ?>">Next Week</a> <!--Next week--> <a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week == 1 ? 52 : $week -1).'&year='.($week == 1 ? $year - 1 : $year); ?>">Pre Week</a> <!--Previous week--> <table border="1px"> <tr> <td>user</td> <?php if($week < 10) { $week = '0'. $week; } for($day= 1; $day <= 7; $day++) { $d = strtotime($year ."W". $week . $day); echo "<td>". date('l', $d) ."<br>". date('d M', $d) ."</td>"; } ?> </tr> </table> Hello,
I've been going about reading different posts on here and other forums but so far I haven't been able to come across something that works for my purpose so after all the reading I thought I'd finally just ask. I'm rather new at php/sql queries so please bare with me.
First what I'm trying to accomplish.
I need a form with several fields (options) to fetch information from a table that will then display the results based on the options selected.
- from date
- to date
- employee name
- department
- branch
- product line
In other words, the purpose is to be able to choose a date range (from one day to up to a year or more) and then to be able to choose either ONE employee name to view statistics invididually from a given department and branch or to select a department to view all the statistics for everyone under that given department and/or brach and/or product line.
Now the tricky part is that besides fetching the records, calculations need to be made before the records are displayed and that part right here is what is giving me a huge headache.
This is the query that I have.
SELECT report_daily_id, report_date, emp_id, emp_fullname, emp_dept, emp_branch prod_line calls, tk_time, hld_time, ac_time, tran_calls, work_time, tran_rate, ah_time FROM daily_report GROUP BY emp_id, emp_fullname, emp_branch, emp_dept, prod_lineThe calculations based on the date range and one or more of the other options need to give me the following results. SUM(calls) AS 'Total Calls' SUM(tk_time) / SUM(calls) AS 'Talk Time' SUM(hld_time) / SUM(calls) AS 'Held Time' SUM(ac_time) / SUM(calls) AS 'AC Time' SUM(tran_calls) AS 'Total Trans' SUM(tran_calls) / SUM(calls) AS 'Tran Rate' SUM(ah_time) / SUM(calls) AS 'AH Time'I don't know how else to explain myself past this point but if you have any questions, perhaps I can answer it and give more details. Thank you, Hello,
Got a code, need to insert a query for displaying links of posts in section. Category is 'blog', each post has it's 'id', and 'subject', which should be a name for link, such as "blog.php?p='id'".
<!doctype html> <html lang="en"> <head> </head> <body class="base"> <div class="container"> <!-- PRZETWARZANIE WYNIKÓW Z BAZY --> <?php $total_pages = $link->query('SELECT * FROM news WHERE category="blog"')->num_rows; $page = isset($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1; $num_results_on_page = 1; if ($stmt = $link->prepare('SELECT * FROM news WHERE category="blog" ORDER BY date DESC LIMIT ?,?')) { $calc_page = ($page - 1) * $num_results_on_page; $stmt->bind_param('ii', $calc_page, $num_results_on_page); $stmt->execute(); $result = $stmt->get_result(); } while ($row = $result->fetch_assoc()): $text = $row['news']; $text = str_replace('[video]','<div class="video-container">',$text); $text = str_replace('[/video]','</div>',$text); $text = str_replace('[media]','',$text); $text = str_replace('[/media]','',$text); $embera = new \Embera\Embera(); echo '<div class="container"> <div class="row">'; ?> <div class="col-sm-4"> /* here is a place for links to published posts */ </div> <?php echo '<div class="col-sm-8"><h3>'.$row['subject'].'</h3>'; echo '<div class="tresc embed-responsive">'; echo $embera->autoEmbed($text); echo '</div></div> </div> </div>'; endwhile; ?> <!-- KONIEC PRZETWARZANIA WYNIKÓW Z BAZY --> <hr class="pagination_divider"> <center> <!-- PAGINATION --> <?php if (ceil($total_pages / $num_results_on_page) > 0): ?> <div class="sect_paginate"><ul class="pagination"> <?php if ($page > 1): ?> <li class="prev"><a href="blog.php?page=<?php echo $page-1 ?>">◂ WSTECZ</a></li> <?php endif; ?> <li class="currentpage"><a href="blog.php?page=<?php echo $page ?>"><?php echo $page ?></a></li> <?php if ($page < ceil($total_pages / $num_results_on_page)): ?> <li class="next"><a href="blog.php?page=<?php echo $page+1 ?>">DALEJ ▸</a></li> <?php endif; ?> </ul></div> <?php endif; $stmt->close(); ?> </center> <!-- END OF PAGINATION --> </div> </body> </html>
Hi, I am having problems returning values from a select statement. When I query directly in the databse, I get back the information I am looking for. I use an includes file for the database connection and my page shows that the connection was successful. Here is my code: Code: [Select] <?php $search = $_GET['searchFor']; $words = explode(" ", $search); $phrase = implode("%' AND articlename LIKE '%", $words); $sql ="SELECT * FROM articles WHERE articlename LIKE '%phrase%'"; $result =$conn->query($sql) or die('Sorry, could not get any articles at this time'); $row =($result->fetch_all()) or die('No records found'); $numRows =$result->num_rows; If($numRows==0) { echo "<h2>Sorry, no articles were found with '$search' in them.</h2>"; } else { While($row=$result->fetch_assoc()) { $articleid = $row['articleid']; $title = $row['articlename']; $shortdesc = $row['shortdesc']; echo "<h2>Search Results</h2><br><br>\n"; echo "<a href=\"index.php?content=showarticle&id=$articleid\">$title</a><br>\n"; echo "$shortdesc<br><br>\n"; } } ?> The search term is coming from a search form in the navigation. I have used "echo" statements to check and make sure that the sesrch word is coming through to tghe page containing the above code. I have tried mysqli_error() statements in several places and don't see where the problem is. When I try the search the message that comes back is "No records found" Does not makee sense because I know it is there, can find it, and even have the same syntax as the SELECT statement I use when I ask for the php code. Going crazy trying to sort this out. Any suggestions, help etc are greatly appreciated. Thank youi. I have a function that performs a SELECT query on a MySQL database and populates the results in an array of Class. At the moment it is using PDO. Trouble is that PDO is not supported by the server the code will run on. Changing server is not an option, nor is installing PDO.
I have tried splitting the function to use the PDO method if installed or MySQLi if not. I am struggling to get the MySQLi part working though. Can anyone help me with this?
Here is the function I have so far which basically returns nothing from the MySQLi part:
public function mysqlSelectToClass($query, $className, $args = NULL) { include (dirname(__FILE__) . "/../config.php"); if (class_exists('PDO')) { $db = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name . ';charset=utf8', $db_user, $db_pass); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbQuery = $db->prepare($query); if (isset($args)) { foreach ($args as $arg) { $dbQuery->bindParam(array_values($arg)[0], array_values($arg)[0], PDO::PARAM_STR); } } $dbQuery->execute(); return $dbQuery->fetchAll(PDO::FETCH_CLASS, $className); } else { $db = mysqli_connect($db_host, $db_user, $db_pass, $db_name); $dbQuery = $db->prepare($query); if (isset($args)) { // Type is a string of parameter types e.g. "is" $type = array_values($args)[0]; // Params is an array of parameters e.g. array(1, 'value') $params = array_values($args)[1]; call_user_func_array('mysqli_stmt_bind_param', array_merge(array($dbQuery, $type), $this->byrefValues($params))); $result = mysqli_stmt_execute($dbQuery); mysqli_close($db); } elseif ($dbResult = mysqli_query($db, $query)) { $result = mysqli_fetch_object($dbResult, $className); mysqli_close($db); } return $result; } }the byrefValues function is simply swapping a value array to a reference array and seems to be working fine. I can paste that too if required. Thanks Jay Edited by jay20aiii, 24 September 2014 - 12:41 PM. Hi,
So I'm not very familiar with using mySQLi, but I'm wanting to print a user's last name, depending on which user is logged in (obviously it needs to be their last name and not another users)
So, we're getting the session for the user and saving their username as $username
$user = Session::Get('current_user'); $username = $user->Get('username');And then my query to display their lastname? $result = $db->Select('lastname')->Where('username', '$username')->Get(Config::Get('db.table')); print_r($result)But the query doesn't work, no error? Forgive my ignorance! >.< Hello guys, i'm currently building my own cms, a personal project, and now im stucked on an error "Call to a member function query() on a non-object in.. please help
after creating this function.. I know the db connection and everything else worked out because i have a similar function that works just without the switch or the numrow if statement.
protected function _pageStatus($option, $id){ //check if page exists, if it does return the status, or return 404 switch($option){ case 'alpha' : $sql = "SELECT status FROM pages WHERE nick = '$id'"; break; case 'num' : $sql = "SELECT status FROM pages WHERE id = '$id'"; break; } if($result = $this->_db->query($sql)){ //<--- THE ERROR WAS ON THIS LINE. if($result->num_rows > 0){ while ($status = $result->fetch_object()) { return $status; } return $status; $result->close(); } else { return 404; } } } |