date range in Mysql (between) - mysql

I want to get all the values in the database where date is between two given parameters. Following is my code. Here Date is $date1' and '$date2 are the given parameters.
$result1 = mysql_query("SELECT * FROM model WHERE Date BETWEEN('$date1' AND '$date2')");
while($row=mysql_fetch_array($result1)){
$d=$row['Date'];
echo $d;
}

You have an error in your syntax. Remove the parentheses after between:
$result1 = mysql_query("SELECT * FROM model WHERE Date BETWEEN '$date1' AND '$date2' ");
I'm guessing this is your question.

Related

Mysql PDO (Getting total from all colums) [duplicate]

I'm new to php and I've searched for the past hour and read all the documentation I could find and nothing is helping. I have a table that has a bunch of rows of data. I'm trying to pick one column from the whole table and add them all together. Here is what I got. All this tells me is how many rows there are that match my query, not the total sum of column I want. Any help is appreciated.
$res1 = $db->prepare('SELECT sum(distance) FROM trip_logs WHERE user_id = '. $user_id .' AND status = "2"');
$res1->execute();
$sum_miles = 0;
while($row1 = $res1->fetch(PDO::FETCH_ASSOC)) {
$sum_miles += $row1['distance'];
}
echo $sum_miles;
You're only returning one row in this instance. Modify your summed column to have an alias:
SELECT SUM(distance) AS totDistance FROM trip_logs ....
Now you can can fetch the row -
$row = $res1->fetch(PDO::FETCH_ASSOC);
echo $row['totDistance'];
No need to loop.
You can use SUM() without explicitely grouping your rows because if you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.
If however you want to use the SUM() function for something slightly more complicated you have to group your rows so that the sum can operate on what you want.
If you want to get multiple sums in a single statement, for example to get the distance for all users at once, you need to group the rows explicitely:
$res1 = $db->prepare("
SELECT
SUM(distance) AS distance,
user_id
FROM trip_logs WHERE status = '2'
GROUP BY user_id
");
$res1->execute();
while ($row = $res1->fetch(PDO::FETCH_ASSOC))
{
echo "user $row[user_id] has runned $row[distance] km.\n";
}
This will return the sum of distances by user, not for all users at once.
Try this if you are using a Class :
class Sample_class{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function GetDistant($user_id,$status) {
$query = $this->db->prepare("SELECT sum(distance) FROM trip_logs WHERE user_id =? AND status =?");
$query->bindValue(1, $user_id);
$query->bindValue(2, $status);
try{ $query->execute();
$rows = $query->fetch();
return $rows[0];
} catch (PDOException $e){die($e->getMessage());}
}
}
$dist = new Sample_class($db);
$user_id = 10;
$status = 2;
echo $dist->GetDistant($user_id,$status);

to find a value within the array in mysql

i want to search data in an array .How can i search using mysql select command. i wrote the query as
$this->db->query("SELECT * FROM client_details WHERE dob IN ({implode(',', $data})");
$data is an array of dates .Please Help me for solving this..
try with
$data =array('0'=>'2015-01-23','1'=>'2015-01-22','2'=>'2015-01-21');
$tmp = implode('","', $data);
$tmp ='"'.$tmp.'"';
$sql= 'SELECT * FROM client_details WHERE dob IN ('.$tmp.')';
echo $sql;
$this->db->query($sql);
You can do something like this:
Option 1
$tmp = implode(',', $data);
$this->db->query("SELECT * FROM client_details WHERE dob IN ($tmp)");
Option 2
$this->db->query("SELECT * FROM client_details WHERE dob IN (".implode(',', $data).")");
Also, there is a mistake in your bracket formation.
It should be dob IN ({implode(',', $data)}"); [Curly braces should close after the closing parenthesis].

CanĀ“t retrieve the date from MySQL

I do an INSERT into mySQL database like this:
$sDate=date("Y-m-d h:i:s");
INSERT INTO tbl_1 (datum) VALUES ('$sDate')
And it'll do the INSERT
But then when I try to find out the unique ID by selecting the date like this:
SELECT id AS nyPost FROM tbl_1 WHERE datum ='$sDate'
It will return nothing, not even an error message. The datum format is datetime.
Please whats wrong?
CODE:
<?php
$sDate=date("Y-m-d h:i:s");
echo $sDate;
If ($strNy)
{
$_nyPrSQL="INSERT INTO begagnads (`anvId`, `tabort`, `datum`) VALUES ('8' , 'null', '$sDate')";
// echo $_nyPrSQL;
if (!mysqli_query($con,$_nyPrSQL))
{die('Error: ' . mysqli_error($con));}
else
{
echo "<br>1 record added";
}
$result = mysqli_query($con,"SELECT id FROM begagnads WHERE DATE(datum) ='$sDate' ");
while($row = mysqli_fetch_array($result)) {
echo $row['id'] . " " . $row['datum'];
$nyPost= $row['id'];
echo "<br>";
}
?>
MySql DATE() function Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03');
-> '2003-12-31'
If you want to find by DATE only
SELECT id FROM begagnads WHERE DATE(datum) = DATE('$sDate')
And if you find with date and time then no need DATE() function
SELECT id FROM begagnads WHERE datum = '$sDate'
You need this:
INSERT INTO tbl_1 (datum) VALUES ($sDate)
Try looking at your table named tbl_1 after the above, by using:
SELECT * FROM tbl_1

How to retrieve items in a manually-specified order

I have a list of id's in PHP. For example:
$id = (4,6,3,2,5,1)
When I perform a query like this:
$query = mysql_query("SELECT * FROM table WHERE ID IN ($id)");
it retrieves the results I want but the items are returned in the insertion order.
Instead, I want to retrieve the results in the order given in my array:
information 4, information 6, information 3, information 2, information 5, information 1
How can I do that?
Thanks guys! solution is ORDER BY FIELD (ID, $id);
Try this
$query = "SELECT * FROM table WHERE ID IN ($id) ORDER BY FIELD(ID,$id) ";
you can see this http://marco-pivetta.com/mysql-custom-sorting-rule-mysql/
$query = "SELECT * FROM table WHERE ID IN ($id) ORDER BY ";
foreach ($id as $i) {
$query .= "ID = $i,";
}
$query = mysql_query(rtrim($query, ','));
Your code is vulnerable to injection. You should use properly parameterized queries with PDO or mysqli.
You can use FIELD on this,
SELECT *
FROM table
WHERE ID IN (4,6,3,2,5,1)
ORDER BY FIELD(ID, 4,6,3,2,5,1)
Custom Sorting using FIELD() example
$query="SELECT * FROM table WHERE ID IN ($id) ORDER BY FIND_IN_SET(ID,$id) DESC";
Also check this
Select query using IN() and without any sorting

Can you have an OR in a WHERE statement inside a mysql query?

Is it possible to have an OR inside a WHERE statement in a mysql query as I have done below.
$query = mysql_query("SELECT * FROM fields WHERE post_id=$id OR post_id="" order by id desc") or die(mysql_error());
This produces a server error when run on my site. Any thoughts on how I could accomplish this?
Thanks in advance.
Yes you can have an OR. What is the type of post_id?
If post_id is a character type:
"SELECT * FROM fields WHERE post_id='$id' OR post_id='' order by id desc"
If it's an integer then it can't be equal to the empty string. Did you mean post_id IS NULL instead?
What is the error? It looks like you have not escaped the double quote in the query. It should be:
$query = mysql_query("SELECT * FROM fields WHERE post_id=$id OR post_id=\"\" order by id desc") or die(mysql_error());
what are the errors.. as such ur query is fine but u string problems with all these double quotes.. try something like this..
$query = mysql_query("SELECT * FROM fields
WHERE post_id = " . $id . " OR post_id='' order by id desc")
or die(mysql_error());