Is it possible to create dates with variables from the post? To goal is to select a date range based on a form. Here's what I have so far:
<?php
include 'inc/connect.php';
if(isset($_POST['rapport-taxes']))
{
$year=$_POST['year'];
$Q2_start_create=date_create($year"-04-01");
$Q2_end_create=date_create($year"-06-30");
$Q2_start=date_format($Q2_start_create,"Y/m/d");
$Q2_end=date_format($Q2_end_create,"Y/m/d");
$test="SELECT * FROM devis where `fp_date` > '$Q2_start' and `fp_date` < '$Q2_end'";
$query=mysqli_query($conn, $test);
echo $query;
}
?>
Any ideas?
There can be hundreds of way but I am just helping you in what you are doing.
You missed concatenation of year, in the below line.
$Q2_start_create=date_create($year"-04-01");
//$year and "-04-01", to concatinate both you need to put a .
See the below code, run it once. echo is just to check so remove it later.
$year="2005";
$Q2_start_create=date_create($year."-04-01");
$Q2_start=date_format($Q2_start_create,"Y/m/d");
echo $Q2_start;
PHP doesn't enforces date datatype. date_format(); will be returning string so you could just build a string and pass it to the query as long as the code you have posted is the only thing you want to get done.
<?php
include 'inc/connect.php';
if(isset($_POST['rapport-taxes']))
{
$year=$_POST['year'];
$Q2_start= $year . "/04/01";
$Q2_end= $year . "/06/30";
$test="SELECT * FROM devis where `fp_date` > '$Q2_start' and `fp_date` < '$Q2_end'";
$query=mysqli_query($conn, $test);
echo $query;
}
?>
Related
I have a database that holds thousands of structures. The structures are searchable by choosing the "area" first, then selecting the "block_number". My first page allows the user to select the area, the area is then passed through the url to the next page. The next page uses php to pull up the blocks in that area. I'm trying to echo the "area" and "block_number" in the results. The my query works just fine but, for some reason I can't display the "area" in the results. See the code below.
<?
include("conn.php");
include("pl_header.php");
$area = mysql_real_escape_string($_GET['area']);
$wtf = '$area';
?>
<h3>Choose A Block Number in<br> <?=$area?></h3><br>
<center>
<?php
$tblWidth = 1;
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
$i = 1;
// Check to see if any results were returned
if(mysql_num_rows($sql) > 0){
echo '<div class="redBox extraIndent">';
// Loop through the results
while($row = mysql_fetch_array($sql)){
echo ''. $row['area'] .''. $row['block_number'] .'';
if($i == $tblWidth){
echo '';
$i = 0;
}
$i++;
}
echo '';
}else{
echo '<br>Sorry No Results';
}
?>
</div>
</body>
</html>
My issue is where you see '. $row['area'] .' displays nothing, but the '. $row['block_number'] .' works just fine.
Your query is only selecting block_number.
Try changing:
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
To:
$sql = mysql_query("SELECT DISTINCT block_number, area FROM platform_locations WHERE area='$area'");
Edit: If you have this issue in the future try var_dump($row); to see what the array contains. This would show you that you only have access to the block_number and not the area.
Double edit: I didn't notice, but the other answer is right about the $area var- you've already got the $area saved, use that variable instead of the return from the DB as it's already in memory. If this could change per record, it'd be prudent to use the record's area variable to make your code more reusable. However, in this particular case, your SQL statement has the area in the where clause, so it wont vary unless you attempt to use portions of this code elsewhere.
Your SQL query is only selecting block_number, so that's the only field that will be in the $row array. You've already got area as a variable $area so use that, not $row['area'].
I have a mysql database with a field called DATE, storing data as a date. I am trying to get the php date to select records for the next 31 days from the current date.
This is what I have...
$start_THISMONTH = "-1";
if (isset($to_date)) {
$start_THISMONTH = $to_date;
}
$finish_THISMONTH = "-1";
if (isset($from_date)) {
$finish_THISMONTH = $from_date;
}
mysql_select_db($database_WHTSON, $WHTSON);
$query_THISMONTH = sprintf("SELECT * FROM CALENDAR WHERE DATE BETWEEN %s AND %s AND APPROVED = 1 ORDER BY DATE ASC", GetSQLValueString($start_THISMONTH, "date"),GetSQLValueString($finish_THISMONTH, "date"));
$THISMONTH = mysql_query($query_THISMONTH, $WHTSON) or die(mysql_error());
$row_THISMONTH = mysql_fetch_assoc($THISMONTH);
$totalRows_THISMONTH = mysql_num_rows($THISMONTH);
-
The code to set up the two variables is
$from_date = date("Y-m-j");
$to_date = date('Y-m-j', strtotime("+31 days"));
And my php code in the body is
<h4><strong><font color="#FF0000"><?php echo $row_THISMONTH['EVENT_NAME']; ?></font></strong></h4>
<?php $date = date_format($row_THISMONTH['DATE'], 'jS F'); ?>
<h5><em><?php echo $date; ?>, <?php echo $row_THISMONTH['TIMES']; ?><br />
<?php echo $row_THISMONTH['LOCATION_ADDRESS']; ?>, <?php echo $row_THISMONTH['LOCATION_TOWN']; ?> <?php echo $row_THISMONTH['LOCATION']; ?></em><br />
</h5>
<p><?php echo $row_THISMONTH['EVENT_DETAILS']; ?><br />
</p>
No results are showing up. This is a new build database, and only one record is in there, with a date of Valentines Day. If I change the code to a simple "find all records" query it shows up great (though the date_format doesn't display a date.
This is my nemesis, please help me understand what I've done wrong?
If you have a date field column in mysql(YYYY-MM-DD) then try date('Y-m-d') instead of date('Y-m-j')
I have been staring at this for so long, but I think I have found one answer. I tried to be logical and use $to_date and $from_date, and then put them in the wrong order in the query. So although I haven;t actually solved the issue, I thinnk the issue is my untidyness on this occasion. I learnt a lot from the discussion too, thank you very much - time for a cleen sheet and a slower pace :)
All the whole day I'm trying to solve this problem but still no luck.
The scenario is: I am developing a vertical menu which should query groups and items of those groups in a menu respectively, but groups are being populated without its items.
Code was written in the following way:
$data1 = mysql_query(select groupnames from groups where categoryy='Agriculture');
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$data2==mysql_query(select itms from groupitems where categoryy='Agriculture' and groupname='$info1[0]');
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
In the above code, groups are being populated nicely but no items from groupitems table are being populated. If I write Grain (Grain is one of the group of agriculture in my database) instead of groupname=$info1[0] then it works. But it should be got dynamically from the query.
Please help, I'm in trouble.
at last its solved! here's the code:
<?php
include "aPannel/dbconn.php";
$query="select GroupName from categorygroup where categoryy='Agriculture'";
$i=0;
$result=mysql_query($query);
$num=mysql_num_rows($result);
$groupname=mysql_result($result ,$i ,"GroupName");
mysql_close();
if ($num=="0") echo "<p>Sorry, there are no groups to display for this Category.</p>";
else
{
echo "<p>There are currently <strong>$num</strong> groups represented in our database.</p><br>";
while($i < $num)
{
$groupname=mysql_result($result ,$i ,"GroupName");
include("aPannel/dbconn.php");
$query2 = "SELECT subcategory FROM groupsubcategory WHERE groupname='$groupname'"; // count number of items in each group
echo $query2 . "<br/>";
$resultt=mysql_query($query2);
$countt=mysql_num_rows($resultt);
mysql_close();
echo $countt . "subcategories" . "<br/>"; // display number of items
$i++;
}
} // end if results
?>
Your queries are not wrapped around double-quotes (" ") . Always remember that what you pass to mysql_query method is a string argument. And also $data2==.... seems wrong.
So, change the code like this
$data1=mysql_query("select groupnames from groups where categoryy='Agriculture'");
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$infoTemp=$info1[0];
$data2=mysql_query("select itms from groupitems where categoryy='Agriculture'
and groupname='$infoTemp'");
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
I hope it should work
EDIT: Also are you sure column itms in second query or items ?
EDIT: added temporary variable
I have recently noticed on my website that a news page is repeating news articles from all "May"'s in the database (you will notice by looking here: www.darlingtontowntwinning.co.uk/news_&_events)
I know that the coding is messy and possibly out of date, however, the website was built for us, and I don't have the skills (yet - I am learning!) to change the entire website at this time.
Is there a way to stop this from occuring - since I believe I have already got a limit of one of each record to display:
<div id="right" class="news">
<h3>Archive</h3>
<? $news=$session->getNews("","","",1);?>
<? while($article=mysql_fetch_array($news)){?>
<?
$date = $article['thedate'];
$year = date('Y', $date);
$month = date('F', $date);
?>
<h4><?=$month." - ".$year;?></h4>
<nav class="small">
<? $innernews=$session->getNews("",$month,$year);?>
<? while($innerarticle=mysql_fetch_array($innernews)){?>
<a href="/news/<?=$innerarticle['ftitle']?>" <? if($title==$innerarticle['ftitle']){?> class="active"<? }?>><?=$innerarticle['title']?></a>
<? }?>
</nav>
<? }?>
</div>
Get news function is:
function getNews($title,$month,$year,$group){
global $database;
return $database->getNews($title,$month,$year,$group);}
$database->getNews function is:
//get news
function getNews($title,$month,$year,$group){
if($title){
$q=$this->query("SELECT * FROM ".TBL_NEWS." WHERE ftitle = '$title'" );
return mysql_fetch_array($q);
}else if($year && $month){
$q=mysql_query("SELECT * FROM ".TBL_NEWS." WHERE (FROM_UNIXTIME(thedate, '%Y') = '$year') AND (FROM_UNIXTIME(thedate, '%M') = '$month') ORDER BY thedate DESC");
return $q;
}else if($group){
$q=$this->query("SELECT * FROM ".TBL_NEWS." GROUP BY (FROM_UNIXTIME(thedate, '%Y')),(FROM_UNIXTIME(thedate, '%M')) ORDER BY thedate DESC" );
return $q;
}else{
$q=$this->query("SELECT * FROM ".TBL_NEWS." ORDER BY thedate DESC" );
return $q;
}
}
The code appears to be working
//get news from group 1
$news=$session->getNews("","","",1);
// for each article work out the date
while($article=mysql_fetch_array($news))
$date = $article['thedate'];
$year = date('Y', $date);
$month = date('F', $date);
...
// then select everything again after working out the date (odd way of doing it)
$innernews=$session->getNews("",$month,$year);
// and output each
So, because there are two event in May, it's outputting the header twice. Let me go over that...
Get news grouped by date (allegedly)
June, just 1 article
1:
Output the header
Select the articles
Output the article
May, 2 articles
1:
Output the header
Select the articles
Output the article
2:
Output the header
Select the articles
Output the article
This group by SELECT * FROM ".TBL_NEWS." GROUP BY (FROM_UNIXTIME(thedate, '%Y')),(FROM_UNIXTIME(thedate, '%M')) ORDER BY thedate DESC is not behaving as expected and is returning two results for May
Try this code
<div id="right" class="news">
<h3>Archive</h3>
<?
$news=$session->getNews();
$bydate=array(); // articles by date
while($article=mysql_fetch_array($news)){
$k=date('YF', $date);
if (!isset($bydate[$k])) $bydate[$k]=array(); // create sub array
$bydate[$k][]=$article; // push article to this sub array
}
foreach ($bydate as $date->$articles){ // run through top array
?><h4><?= substr($date,4) . " - " . substr($date,0,4); ?></h4><nav class="small"><?
foreach ($articles as $innerarticle){ // now each article within this date
?><a href="/news/<?=$innerarticle['ftitle']?>" <? if($title==$innerarticle['ftitle']){?> class="active"<? }?>><?=$innerarticle['title']?></a><?
}
?></nav><?
}
?></div>
and please change
function getNews($title,$month,$year,$group){
to
function getNews($title=NULL, $month=NULL, $year=NULL, $group=NULL){
Welp. There's your problem.
Your function says, if($title). Since $title comes in as a required parameter in the function, I think PHP is registering it as, yes, that's a variable that is set. So, basically what happens, then, is you're getting back a mysql_fetch_array result, which you are then running mysql_fetch_array for a second time.
Try:
//in your function getNews()
if($title){
$q=$this->query("SELECT * FROM ".TBL_NEWS." WHERE ftitle = '$title'" );
return $q;
}
//rest of function down here
That could work. The issue I see is, doing that, you WILL CAUSE ISSUES ANYWHERE ELSE THAT FUNCTION IS CALLED. So be careful! The fix above is the fix to ensure you get code into a better state. If you want a hack, try this:
<? $innernews=$session->getNews("",$month,$year);?>
<? foreach($innernews as $innerarticle) {?>
<a href="/news/<?=$innerarticle['ftitle']?>" <? if($title==$innerarticle['ftitle']){?> class="active"<? }?>><?=$innerarticle['title']?></a>
<? }?>
The foreach loop should give you what you want!
It's been a month and am really messed up trying to integrate a php pagination code to my search script. Referred to most of the tutorials Googling, but in vain. Any help would be much appreciated. Here I go...
<?php
ob_start();
session_start();
$_GET['term'] = trim($_GET['term']);
$output = preg_replace('!\s+!', ' ', $_GET['term']);
if(empty($_GET['term'])|| preg_match("/^[#!#\$\^%&*()+=\-\[\]\\\';,\.\/\{\}\|\":<>\?\ _ ]+$/i", $_GET['term']) || $output== ' ' || $_GET['term']== "%24_GET%5B%27term%27%5D")
{
echo "<BR>";
echo "<BR>";
echo("Please enter a Valid Search term");
}
else
{
mysql_connect("localhost", "root", "root");
mysql_select_db("search");
$_GET['term'] = explode(' ', $_GET['term']);
foreach($_GET['term'] AS $_GET['term'])
{
$_GET['term'] = trim($_GET['term']);
$sql = mysql_query("SELECT DISTINCT * FROM searchengine WHERE pagecontent LIKE '%" . str_replace(' ', "%' AND pagecontent LIKE '%", $_GET['term'])."%' LIMIT 0,10");
while($ser = mysql_fetch_array($sql)) {
echo "<BR>";
echo "<b><u><a href='$ser[pageurl]'>$ser[title]</a></u></b>";
echo "<BR>";
echo("<span class='style_block'>{$ser['pagecontent']}</span>");
echo "<BR>";
echo ("<a href='$ser[pageurl]'>$ser[pageurl]</a>");
echo "<BR>";
echo "<BR>";
}
}
$count=mysql_num_rows($sql);
if($count==0)
{
echo "<BR>";
echo "<BR>";
echo "Sorry, No News material was found... Please refine your search criteria and try again.";
}
}
?>
Apart from the problems Luc M has mentioned in his comment (which you should certainly resolve before moving forward), you are almost there.
You need to consider a couple of points, really: How many records to display per page, and what page you are on. These will dictate the records you need to retrieve and display. So, how do you go about this?
The first point is covered in your code already through use of the LIMIT clause in your SQL query. The second point is a tiny bit more complex to start with. You need a way of identifying the page you are on. This is probably easiest to identify through a GET variable, for example http://site.com/search.php?page=2. Now, for implementing this, you want something along these lines:
$recordsPerPage = 10; // although you may want to have this as a GET or POST variable as well, so the user can decide
if(isset($_GET['page']) // this ensures a default value
{
$currentPage = $_GET['page'];
}
else
{
$currentPage = 1;
}
Then, for your SQL query, you want to build something like this:
$query = "SELECT * FROM table_name LIMIT " . $recordsPerPage . " OFFSET " . ($currentPage - 1)*$recordsPerpage . ";";
The OFFSET clause of SQL along with LIMIT basically says "Select this many records, starting from result number x". You offset on $currentPage - 1 because the first page doesn't want an offset, and the second page only wants an offset of however many records were shown on the first page, so on and so forth.
To create navigation for the paginated data, you want to find out how many records are in your result set, which can be done through the count($array) function of PHP. Then, to find the number of pages, simply use something like:
$numPages = ceil(count($array)/$recordsPerPage);
Where $array is your dataset from the SQL query. The ceil() function rounds the result up to the next integer.
Once you have this result, you simply need to output links to each page, which can be done simply with a for loop:
for($i = 0; i < $numPages; i++)
{
echo '<a href="/search.php?page="' . $i+1 . '>' . $i+1 . '</a>';
}
To create first, previous, next and last page links, you need to do something like:
$firstPage = 1;
$previousPage = $currentPage - 1; // you may want to check here or elsewhere to make sure you have no page zero
$nextPage = $currentPage + 1; // may also want to make sure you don't go past the last page
$lastPage = $numPages;
These values can then be put into your generated links.
Again, I will refer you to Luc M's comment... These need to be fixed, take a look at mysqli functions instead of the now-deprecated mysql_*() functions you're currently using, make sure you clean any user-inputted data before using it, and consider looking at the MVC design pattern.
Hopefully, this will help you out.