PHP - Querying Db For Particular Month In Datetime
Hi all,
I am currently storing dates and times for certain events in the following format: $now= date('Y-m-d H:i:s'); This variable is then stored in a MySQL field of type DATETIME. I am looking for a way to query the database to return all results in a certain month, or within a certain time range, or a certain year etc. How would this be achieved? e.g. If I wanted to select everything for the year 2009, would it be: SELECT * FROM table WHERE date BETWEEN '2009-01-01 00:00:00' AND '2009-12-31 11:59:59' ? Thanks! Similar TutorialsI am using the following code to get the third sunday of every month for +6 Months from todays date. I have put together the following code which works perfectly when the date is echoed however when it comes to inserting those dates into mysql db it throws a unable to convert to string error. Im new to this and my head is in a spin as to why those dates can't be inserted if they can echoed ok. I have spent 2 days at it now and searched many forum however they seem to get side tracked from my issue (or do they)??????? I figure I can't go mixing DateTime and date() the way I have? Please help??? Code: [Select] [php] $month=date('F'); $now=date('Y-m-d'); $year=date('Y'); $num='3'; //example only this will be a $_POST value 0-3 $day='Sunday'; //example only this will be a $_POST value Monday-Sunday $start= date('Y-m-d', strtotime('+'.$num.' week '.$day.' '.$month.' '.$year.'')); if($start>$now) { $begin=strtotime('+'.$num.' week '.$day.' '.$month.' '.$year.''); } else { $d = new DateTime( $start ); $d->modify( 'first day of next month' ); $nextmonth = $d->format( 'F' ); $year = $d->format( 'Y' ); $begin=strtotime('+'.$num.' week '.$day.' '.$nextmonth.' '.$year.''); } $date=date('Y-m-d', $begin); # insert into db first occurance //mysql_select_db($database); //$query_rsFirst = "INSERT INTO event_date VALUES (NULL, '$event', '$d', '$date', '$date')"; //$rsFirst = mysql_query($query_rsFirst) or die(mysql_error()); echo $date.'<br/>'; for($i = 0; $i <= 4; $i++) { $d = new DateTime( $date ); $d->modify( 'first day of next month' ); $nextmonth = $d->format( 'F' ); $date=date('Y-m-d', strtotime('+'.$num.' week '.$day.' '.$nextmonth.' '.$year.'')); # insert into db //mysql_select_db($database); //$query_rsDate = "INSERT INTO event_date VALUES (NULL, '$event', '$d', '$date', '$date')"; //$rsDate = mysql_query($query_rsDate) or die(mysql_error()); echo $date.'<br/>'; if($nextmonth=="December") { $d = new DateTime( $date ); $d->modify( 'first day of next year' ); $year = $d->format( 'Y' ); } } [/php] Dear all, how can I convert a string "yyyy-mm-dd hh:mm" into a really datetime value with php? thanks! Trying to get the below to generate the month in word form from a numeric entry in a database. Code: [Select] elseif($_GET['rma']=="calander"){ $sql101010="SELECT DISTINCT rma_year_issued FROM $tbl_name4 ORDER BY rma_year_issued"; $result101010=mysql_query($sql101010); while($row101010=mysql_fetch_array($result101010)){ extract($row101010); $content.='<a href="./acp_admincp.php?rma=calander&year='.$rma_year_issued.'">'.$rma_year_issued.'</a> <br />'; } if(isset($_GET['year'])){ $logout.=' | <a href="./acp_admincp.php?rma=calander">Back to RMA Calander</a>'; $rma_year_issued=$_GET['year']; $sql111010="SELECT DISTINCT rma_month_issued FROM $tbl_name4 WHERE rma_year_issued='$rma_year_issued' ORDER BY rma_month_issued"; $result111010=mysql_query($sql111010); while($row111010=mysql_fetch_array($result111010)){ extract($row111010); $months = array('Janurary', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); for($i=0; $i <=11; $i++){ if($rma_month_issued=$i){ $rma_month_issued2=$months[$i]; } } $content=""; $content.='<a href="./acp_admincp.php?rma=calander&year='.$rma_year_issued.'&month='.$rma_month_issued.'">'.$rma_month_issued2.'</a> <br />'; } } } Basically in the data base I may have 2,5,7 under the year 2011. I want to get the numeric months into words for use in the text of the link. The above is returning December even though the entry in the database is 5. Hi.. I need help in getting the 3 Months Name from my table field FromMonth and ToMonth. Here is the scenario. First, I select FromMonth and ToMonth. Ex. FromMonth = 5 ToMonth = 7 So it means FromMonth is May ToMonth is July. Now I save the MonthNumber to my database: table- so_month FromMonth = 5 ToMonth = 7 Now I need to get the between Months Name from FromMonth to ToMonth which are (May, June, July). How does it possible? Thank you so much. So I am creating a list of events. There will be a drop down menu to change between months. I only want the months to be listed if an event during that month exists. So if I have events listed for September and November, list only September and November, skipping October. Any idea on how to approach this or if there are any functions for such a thing? I have put together a query which is designed to display a single question from a database. However, it currently displays all the questions (and notes and category). The problem is I cant work out how to get it to display just the qid I am querying. This should display phpquestion.php?qid=2 but it just displays all the question as does phpquestion.php?qid=7 etc Code: [Select] ini_set('display_errors', 1); error_reporting(-1); $query = "SELECT * FROM questions"; if(isset($_GET['question'])) { $question = $_GET['question']; $query .= " WHEN qid is '$qid' LIMIT 0, 1"; } $result = mysql_query($query); while($row = mysql_fetch_assoc($result)) { $question = $row['question']; $notes = $row['notes']; $category = $row['category']; $qid = $row['qid']; echo "$question | $notes | $category </br> "; } if ($_GET['qid'] == $qid ) { echo 'Sorry, this question is not available. Please visit our <a href="http://www.ukhomefurniture.co.uk">Homepage</a>.'; } function sanitizeString($string) { return mysql_real_escape_string($string); } $question = sanitizeString($_GET['qid']); $query .= " WHERE question is '%$qid%'"; // close connection mysql_close(); ?> Hey all. I'm using this sort of thing to query with my application: Code: [Select] try { $stmt = $this->db->prepare($sql); /* Bind parameter if id was passed, ensure it's of integer type */ if(!empty($id)) { $stmt->bindParam(":id", $id, PDO::PARAM_INT); } $stmt->execute(); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); return $results; } catch(Exception $e) { die($e->getMessage()); }which has been working out great, with the only annoyance that sometimes, I need to run a query and I know I'm supposed to get only one row. However, I have to access associated elements via $results[0]['fieldName']. How do I run a query to return exactly one result so I can just use $results['fieldName']? Hi everyone. I'm a query very similar to the one below with no success. Unfortunately SQLs and joins are not my strong suit. Code: [Select] SELECT f.field1, f.field2, f.field3 FROM fields_table f WHERE f.field1 = SOME_VALUE LEFT JOIN fields_table s ON s.field2 > f.field2 AND s.field3 <= f.field3 LIMIT 1 I would like the first SELECT query to be returned even if there are no matches on the join, also I'd like the second table query to be limited to 1. Is this possible? Could anyone revise the table above to make this work? Thanks! Is it possible to use a 'SELECT FROM' against a query in a new query? For example (and I know this would be bad practice but it is just a simple example so I can understand!!!), if you had a table called 'staff' with this sort of set up ID | NAME | SEX | AGE | DEPARTMENT and this query $staffquery = SELECT * FROM staff would it be possible to then use $males = SELECT * FROM $staffquery WHERE sex = 'Male' $females = SELECT * FROM $staffquery WHERE sex = 'Female' $males_in_despatch = SELECT * FROM $staffquery WHERE sex = 'Male' AND department = 'Despatch' or would I have to run the full query each time? The example I have given is not a good one as it only queries one table anyway but if it was querying several joined tables then it would obviously be a lot of repeated code. I am trying to set up a page which does various counts and sums from a query that links several different tables and I am trying to work out the best way to set it all up before worrying about actually getting the data. I can post the full query that I am actually using and some sample data if required. Thanks in advance Steve Is there a way to query some information depending on if a table field DOES NOT include a specific value? I've got a table that contains over 100 locations. I want to organize the data on the frontend by country (specifically US and International). How would I go about filtering out locations that DO NOT belong in USA? $q = "SELECT * FROM table WHERE COUNTRY='USA'"; Hi, I'm very new to PHP and have managed to get through most of the problems I've encountered so far, but I have got to one point that I can't seem to solve. I have two mysql tables (Categories & Products), I have a page that shows the categories (generated from the categories table) and when a category is selected it lists the products in that category. Due to stock etc. not all categories always have products associated to them. The Category & Product Tables are automatically updated, so what I need to do is only show categories that have products associated to them, both tables have a column category_no, and nothing I've tried so far seems to work. The code I have so far is:- Code: [Select] Require_once('config.php'); Mysql_connect(db_host, db_user, db_password); @mysql_select_db(db_database) or die( "unable to select database"); $query="select * from categories"; $result=mysql_query($query); $num=mysql_numrows($result); Mysql_close(); Thanks Pete I have three tables: events, orderdetails & orders. First I query orderdetails to find all the records that match the EventID: $query1 = SELECT * FROM orderdetails WHERE EventID = $_SESSION['EventID']; This returns 4 records. These 4 records have a field called DetailOrderID which is the foreign key for orders.OrderID. Next I need to query the results of the first query to find all the records in the orders table that match up. For example: SELECT * from orders where $query1.DetailOrderID = orders.OrderID. How would I go about doing this? I'm head down the temporary table solution but wanted to through this one out for discussion before I invest too much time. Here is where I'm starting: Code: [Select] SELECT * FROM wp_usermeta WHERE meta_key = 'wp_1_s2member_custom_fields' AND meta_value LIKE '%3%' As the PHP produces the page, I'm going to have 15 different options coming from the Code: [Select] meta_value LIKE part. I'm assuming I can set up my 15 different DIVs, each with their own IF statement involving the meta_value. Right? I'm not going to have to have 15 different queries, am I? I assume it would start like this: Code: [Select] $query = 'SELECT * FROM wp_usermeta WHERE meta_key = "wp_1_s2member_custom_fields"'; $results = mysql_query($query); while($line = mysql_fetch_assoc($results)) But from there, I don't know if it's possible to deal with partial data with IF statements. Hi guys, I need help in my code, it states 'Error querying database' when I set $result = mysql_query($query, $dbc). And strange thing happens when I switched $query and $dbc place, and I got a different error msg $result = mysql_query($dbc, $query). 'Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in D:\inetpub\vhosts\championtutor.com\httpdocs\report.php on line 31 Error querying database' Any idea what is happening? Below is my code Lastly, do you guys have any debug tool software to recommend, so that it can assist me in debugging my code. Thanks <?php $first_name = $_POST['firstname']; $last_name = $_POST['lastname']; $when_it_happened = $_POST['whenithappened']; $how_long = $_POST['howlong']; $how_many = $_POST['howmany']; $alien_description = $_POST['aliendescription']; $what_they_did = $_POST['whattheydid']; $fang_spotted = $_POST['fangspotted']; $email = $_POST['email']; $other = $_POST['other']; $dbc = mysql_connect('*******', '*******', '*******', '*******') or die('Error connecting to MySQL server.'); $query = "INSERT INTO aliens_abduction (first_name, last_name, when_it_happened, how_long, " . "how_many, alien_description, what_they_did, fang_spotted, other, email) " . "VALUES ('$first_name', '$last_name', '$when_it_happened', '$how_long', '$how_many', " . "'$alien_description', '$what_they_did', '$fang_spotted', '$other', '$email')"; $result = mysql_query($query, $dbc) or die('Error querying database.'); mysql_close($dbc); echo 'Thanks for submitting the form.<br />'; echo 'You were abducted ' . $when_it_happened; echo ' and were gone for ' . $how_long . '<br />'; echo 'Number of aliens: ' . $how_many . '<br />'; echo 'Describe them: ' . $alien_description . '<br />'; echo 'The aliens did this: ' . $what_they_did . '<br />'; echo 'Was Fang there? ' . $fang_spotted . '<br />'; echo 'Other comments: ' . $other . '<br />'; echo 'Your email address is ' . $email; ?> SELECT COUNT( City ) AS Hotel, City, CountryName, Country FROM `activepropertylist` WHERE MATCH(city,Countryname) AGAINST ('South shields*' IN BOOLEAN MODE) GROUP BY City,Countryname,Country ORDER BY City LIMIT 15hi all I have a query against the database table which uses the full text index's and I am limiting this to 15 rows for the ajax problem is it is returning Africa and other things before south shields is there something I am missing as I know South shields is in there when scrolling through all the results here is my query <?php include 'core/classes/Query.php'; include 'core/functions/recaptchalib.php'; $sqlQ = "SELECT * FROM `servers`"; $qResult = $database->query($sqlQ); $i = 0; while ($row = $qResult->fetch_assoc()) { $query = new Query($row['address'], $row['query_port'], $row['engine']); $info = $query->query(); if(!$info) { $info = $query->return_false(); } $details = array( 'players' => $info['players'], 'details' => $info['details'] ); $details = json_encode($details); $update = $database->prepare("UPDATE `servers` SET `status` = ?, `online_players` = ?, `maximum_online_players` = ?, `map` = ?, `details` = ?, `cachetime` = unix_timestamp() WHERE `server_id` = {$row['server_id']}" $update->bind_param('sssss', $query->status, $info['general']['online_players']['value'], $info['general']['maximum_online_players']['value'], $info['general']['map']['value'], $details) $update->execute(); } ?>What I'm trying to accomplish is query every server & update every one of the rows for each server listed. This does nothing ( its a cronjob , as it has to run every 5 minutes , newbie so not entirely sure if this is event the right approach ) Hello, I'm attempting to write a PHP script to query WMI for an IP address of a host. The reason I'm doing this instead of getbyhostname is because NAT translations on the network can cause inaccurate results. The question is two-fold: 1) My Script is as follows <? $obj = new COM ( 'winmgmts://localhost/root/CIMV2' ); $wmi_network = $obj->ExecQuery("Select * From Win32_NetworkAdapterConfiguration"); foreach ( $wmi_network as $wmi_call ) { $ipaddr = $wmi_call->IPAddress; echo $ipaddr; } ?> I get the following error when running the script: Quote Catchable fatal error: Object of class variant could not be converted to string 2) How do I go about querying a remote host on the network with valid credentials? Thank you I've been trying to fix this piece of script so i can query the results from a database. What i want to do is to display the results from the database like below: Product Heading price Subproduct - $price Each item would have a check box next to them. I have managed to display the items but not the prices. I've looked over the code several times but i'm lost on what i should do. Anyway here's the code, i hope someone here can view it and let me know what i'm doing wrong or what i'm not doing. <?php $get_cats = "SELECT * FROM sub_service WHERE industry='$industry'"; $run_get = mysql_query($get_cats) or die(mysql_error()); $tmp = array(); $x=1; while($rw = mysql_fetch_assoc($run_get)){ if (!array_key_exists($rw['service'],$tmp)) { $tmp[$rw['service']] = array(); } $tmp[$rw['service']][] = $rw['sub_service']; } foreach ($tmp as $service => $items) { ?> <div id="industry_wrapper"> <h2><?php echo $service ?></h2> </div> <div id="select_all_holder"> <div id="select_all_input"> <input type="checkbox" class="toggleElement" name="toggle" onchange="toggleStatus()" /> </div> <div id="select_all_txt"> <p>Select All Services - $</p> </div> </div> <?php echo' <div class="service_holder"> <table width="650" cellpadding="0" cellspacing="5"> '; foreach ($items as $cat) { ?> <tr> <td width="28" align="center"><input type="checkbox" /></td> <td width="605"><p><?php echo $cat ?> - $<?php echo $tmp['price']; ?></p></td> </tr> <?php } echo'</table></div>'; } ?> I have a table in a mysql database with 5 columns, id, Name, Wifi, Bluetooth, GPS, with rows that are for example 1, Galaxy S2, yes, yes, yes. So basically i want to build a form that has check boxes (3 checkboxes for wifi bluetooth and GPS respectively) that once selected will query the database depending on which check boxes are selected. I have made the form but need to know what to put in the filter.php to make the results be displayed accordingly. Ideally if anyone knows how i would want it so the results were shown on the same page which i believe u need to use ajax to happen but any help on how to show the results will be greatful. the code for the form i have made is as follows: Code: [Select] <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>test</title> </head> <body> <form action="filter.php" method="post"> <INPUT TYPE=CHECKBOX NAME="option[]" VALUE="Wifi" id="r1">Wifi <INPUT TYPE=CHECKBOX NAME="option[]" VALUE="Bluetooth" id="b1">Bluetooth <INPUT TYPE=CHECKBOX NAME="option[]" VALUE="GPS" id="g1">GPS <input type="submit" name="formSubmit" value="Submit" /> </form> </body> </html> im not sure on how to make the filter.php page but i do have this code for displaying the all the data but i want to kno how to make it only display the data from the choices on the checkboxes Code: [Select] <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>pls work</title> </head> <body> <?php function h($s) { echo htmlspecialchars($s); } mysql_connect("localhost", "root", "") or die (mysql_error()); mysql_select_db("project") or die (mysql_error()); $result= mysql_query('SELECT * FROM test') or die('Error, query failed'); ?> <?php if (mysql_num_rows($result)==0) { ?> Database is empty <br/> <?php } else { ?> <table> <tr> <th></th> <th>Name</th> <th>Wifi</th> <th>Bluetooth</th> <th>GPS</th> </tr> <?php while ($row= mysql_fetch_assoc($result)) { ?> <tr> <td> <a href="uploaded-images/<?php h($row['Name']); ?>.jpg"> <img src="uploaded-images/<?php h($row['Name']); ?>.jpg" alt="test"/> </a> </td> <td><a href="textonly.html"><?php h($row['Name']); ?></a></td> <td><?php h($row['Wifi']); ?></td> <td><?php h($row['Bluetooth']); ?></td> <td><?php h($row['GPS']); ?></td> </tr> <?php } ?> </table> <?php } ?> </body> </html> This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=334481.0 |