MySQL search between 2 dates - php

I am having a wierd issue on a query, I am simply doing a search using 2 dates, I have all the dates in the database formatted in 2012-12-02 00:00:00 mysql format, but it is simply ignoring the AND cslblicstat = '10' AND wcxdate BETWEEN '$date1' AND '$date2' and giving me anything that has the matching class.
$user = $session->username;
if(isset($_POST['carrier'])){
$carrier = $_POST['carrier'];
$class[] = $_POST['class'][0];
$date1 = $_POST['date1'];
$date1 = date("Y-m-d 00:01", strtotime($date1));
$date2 = $_POST['date2'];
$date2 = date("Y-m-d 59:59", strtotime($date2));
foreach( $class as $key){
$query = "SELECT * FROM leads WHERE class1 = '$key' OR class2 = '$key' OR class3 = '$key' OR class4 = '$key' OR class5 = '$key' OR class6 = '$key' OR class7 = '$key' OR class8 = '$key' OR class9 = '$key' OR class10 = '$key' OR class11 = '$key' OR class12 = '$key' AND user = '' AND wccompcode = '$carrier' AND cslblicstat = '10' AND wcxdate BETWEEN '$date1' AND '$date2' LIMIT 100";
$sellead = mysql_query($query)or die(mysql_error());
while($leads = mysql_fetch_array($sellead)){
$arrayl[] = $leads;
$rowid = $leads['ID'];
$update = mysql_query("UPDATE leads SET user = '$user' WHERE ID = '$rowid'")or die(mysql_error());
}
}
}

In SQL, AND operator has higher precedence than OR. I guess that you just need to put the ORed conditions into parentheses:
SELECT *
FROM leads
WHERE (class1 = '$key' OR class2 = '$key' OR ... OR class12 = '$key')
AND user = ''
AND wccompcode = '$carrier'
AND cslblicstat = '10'
AND wcxdate BETWEEN '$date1'
AND '$date2'
LIMIT 100
When in doubt about precedence of operators, use parenthesis (or consult the manual).
You could also write that condition with IN:
WHERE '$key' IN (class1, class2, ... , class12)
AND user = ''
---

In MySQL AND is evaluated before OR. So your WHERE clause is equivalent to this:
SELECT 1 OR 0 AND 0;
The result is true:
+--------------+
| 1 OR 0 AND 0 |
+--------------+
| 1 |
+--------------+
Also, a syntactically simpler method of expressing your OR conditions would be something like this:
WHERE '$key' IN ( class, class2, class3, ... ) AND ... ;
But anytime you have columns like that with numbers, what it really means is that your schema can be improved.

Related

How to match two table columns in sql

I have this code
$db = \Config\Database::connect();
$query = $db->query("select * from g WHERE g_status = '0' ORDER BY g_date ASC Limit 10;");
foreach ($query->getResult() as $g) {
$g_amount = $g->g_amount;
}
$query2 = $db->query("select * from g WHERE p_status = '0' ORDER BY p_date ASC Limit 10;");
foreach ($query2->getResult() as $p) {
$p_amount = $p->p_amount;
}
if($p_amount == $g_amount){
echo "do something";
}else{
echo "No match";
}
Here I am trying to match between table g and table p.... if any column in table g is == any column in table p regardless of the number of column, do something but it always echo "NO match"
I put "Limit 10" in case there is much number of rows in the table, it will only match the first 10th row with the "ordering" command.
Please I need some help.
First, get data as an array
$db = \Config\Database::connect();
$query = $db->query("select * from g WHERE g_status = '0' ORDER BY g_date ASC Limit 10;");
$g_results = $query->getResult('array');
$g_amounts = array_column($g_results,'g_amount');
$query2 = $db->query("select * from g WHERE p_status = '0' ORDER BY p_date ASC Limit 10;");
$p_results = $query2->getResult('array');
$p_amounts = array_column($p_results,'p_amount');
foreach(array_intersect($g_amounts,$p_amounts) as $amount){
echo "do something";
}
Why not use a JOIN and see if it returns something? Not sure if my syntax is correct, I don't do JOINs very often:
SELECT * FROM g g_table JOIN p p_table ON g_table.g_amount = p_table.p_amount WHERE g_table.status = '0' AND p_table.status = '0'

Check type from table between dates MySQL,php

I have table as seen below:
ID, Date, Type
1, 2015-1-1, 2
2, 2015-5-1, 5
3, 2015-8-10, 4
(before 2015-1-1 .... type = default
2015-1-1 <= Date < 2015-5-1 .... type = 2
2015-5-1 <= Date < 2015-8-10 .... type = 5
since 2015-8-10 .... type = 4)
I would like simply check which type is for any $date.
I tryed:
$sql = "SELECT * FROM smlouvy
WHERE Date < '".$date."'
ORDER BY Date LIMIT 1";
$result = MySQL_Query($sql);
if ( mysql_num_rows($result) == 0 ) {
$type = 'default';
}
else {
$row = mysql_fetch_array($result);
$type = $row["Type"];
}
You can try something like:
select ID,date,
case `date`
when `date`<='2015-11-01' then 4
when `date`>='2015-11-01' then 5
else 1 end as `type`
from tbl;
Note: This is just an example,you may need to modify the conditions as per your requirement.
Here is solution (if Date column matches within a certain range):
$dateFrom = '2015-5-1';
$dateTo = '2015-8-10';
// exemplary query
$query = "SELECT type FROM table_name
WHERE $dateFrom <= Date < $dateTo
ORDER BY Date ASC LIMIT 1 ";
// it will return the type of lower date column from range (type = 5)

Drupal count of nodes by type and date?

I am trying to display the total count of one day for a specific node type"
function bootstrap_subtheme_get_node_count($content_type) {
$time = strtotime('yesterday midnight');
$query = "SELECT COUNT(*) amount FROM {node} n ".
"WHERE n.type = :type and n.created => " . $time;
$result = db_query($query, array(':type' => $content_type))->fetch();
return $result->amount;
}
and to print
<?php bootstrap_subtheme_get_node_count('page'); ?>
Please correct me what I am doing wrong?
your code looks good, please make 2 changes
1: change created as you done with type.
2: remove * symbol from count(*) and put nid or other column name as you like, it is good for query performance.
Code example:
function bootstrap_subtheme_get_node_count($content_type) {
$time = strtotime('yesterday midnight');
$query = "SELECT COUNT(nid) amount FROM {node} n ".
"WHERE n.type = :type and n.created => :created";
$result = db_query($query, array(':type' => $content_type,
':created' => $time))->fetch();
return $result->amount;
}

How to list by highest date in PHP

Hey guys so I am having some trouble using the following:
for ($i = 0; $i < count($noncompUsername); $i++)
{
$tsql ="SELECT firstname,lastname,email,phone,statuschangedate FROM csvdata WHERE username = :username ORDER BY statuschangedate";
$tgetmeminfo=$DBH->prepare($tsql);
$tgetmeminfo->execute(array(':username' => $noncompUsername[$i]));
while ($trow = $tgetmeminfo->fetch(PDO::FETCH_ASSOC)){
$csvFirst = $trow['firstname'];
$csvLast = $trow['lastname'];
$csvEmail = $trow['email'];
$csvPhone = $trow['phone'];
$csvDate = $trow['statuschangedate'];
$timediff = strtotime($date) - strtotime($csvDate);
$timediff = floor($timediff/86400);
$sql ="SELECT MailingAdrs FROM insuranceverificationdisclaimer WHERE TraineeUsername = :tusername";
$getmeminfo=$DBH->prepare($sql);
$getmeminfo->execute(array(':tusername' => $noncompUsername[$i]));
while ($row = $getmeminfo->fetch(PDO::FETCH_ASSOC)){
$csvAddrs = $row['MailingAdrs'];
$change = 1;
}
if($change != 1)
{
$csvAddrs = "No address";
}
$change = 0;
echo "$timediff, $csvFirst $csvLast, $csvEmail, $csvPhone, $csvAddrs";
}
echo "
<br>
";
}
Now this works but the part I want to point out is the $tsql ="SELECT firstname,lastname,email,phone,statuschangedate FROM csvdata WHERE username = :username ORDER BY statuschangedate"; - now when I do this and get the integer of the statuschangedate to the current date and print it out as an integer, it is not ordered properly based on the date.
So I need to get this to order by the oldest date on top and as follows...
Thank you!
David
Order the date in descending order (using DESC):
... ORDER BY statuschangedate DESC
If you want to order based on $timediff you should change the ORDER clause to this:
ORDER BY DATEDIFF(:date, statuschangedate)
Granted, this should actually give the same ordering you already had, but you could at least use this expression to save some processing in PHP itself :)

MySQL query receives only 1 result

I have the following code which displays only 1 result. However, I have six rows in my database with product_id = '1'. I'm talking about $order, only one shows up, instead of six. What is wrong?
$get = "SELECT * FROM artikelbestelling WHERE product_id = '1' LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while($row = mysql_fetch_assoc($doget))
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo "<strong>$order</strong><br />";
}
My database structure:
id (primary & autoincrement)(int 11)
product_id (int 11)
number (int 11)
ordernummer (int 11)
as your id is int, you dont need to use ''
$get = "SELECT * FROM artikelbestelling WHERE product_id = '1' LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while($row = mysql_fetch_array($doget))
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo "<strong>$order</strong><br />";
}
try this.....
$get = "SELECT * FROM artikelbestelling WHERE product_id = '1'
LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while($row = mysql_fetch_array($doget))
{
echo "$row[ordernummer]";
echo "<br />";
echo "$row[artikelnummer]";
}
There are two things that I notice immediately that shouldn't make a difference, but might be worth trying just to see if it does. First, assuming that the product_id column is a numeric column instead of a string, try using just 1 instead of '1'. Second, explicitly check the result of mysql_fetch_assoc() against FALSE instead of any expression that might evaluate equivalent to false.
$get = "SELECT * FROM artikelbestelling WHERE product_id = 1 LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while(($row = mysql_fetch_assoc($doget)) !== FALSE)
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo "<strong>$order</strong><br />";
}
Edit:
What do you get if you change your code to the following?
$get = "SELECT * FROM artikelbestelling WHERE product_id = 1 LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
$index = 0;
while(($row = mysql_fetch_assoc($doget)) !== FALSE)
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo $index++ . ": <strong>$order</strong><br />";
}
Specifically, does it count all the way from 0 to 7, or does it just show row 0? I'm thinking that it's got to be one of the following:
You really are only getting back one row of results (which is contradicted by your statement that mysql_num_rows() is returning 8),
mysql_fetch_assoc() is incorrectly returning FALSE after just one row (which indicates some kind of bug affecting PHP or the MySQL driver, which is typically very unlikely), or
it is iterating through the loop like it should be, but you are misinterpreting the result, per Marc B's comment regarding empty tags.
This might effectively help narrow down which it is.

Categories