Convert varchar to date in where clause - mysql

function details_klanten($idKlant,$start,$eind){
$this->db->select(' Project.idProject,
Project.Titel,
Project.idProjecttype,
Project.Begindatum,
Project.Deadline,
Project.idKlant,
Projecttypes.idProjecttypes,
Projecttypes.Type,
Werknemer.idWerknemer,
Werknemer.Voornaam,
Statusproject.idStatusProject,
Statusproject.Soort,
Klant.Naam');
$this->db->order_by('Titel', 'asc');
$this->db->from('Project');
$this->db->join('Klant', 'Klant.idKlant = Project.idKlant');
$this->db->join('Projecttypes', 'Projecttypes.idProjecttypes = Project.idProjecttype');
$this->db->join('Werknemer', 'Werknemer.idWerknemer = Project.idWerknemer');
$this->db->join('Statusproject', 'Statusproject.idStatusProject = Project.idStatusProject');
if ($idKlant > 0){
$this->db->where('Klant.idKlant',$idKlant);
$this->db->where('Project.Begindatum >',$start);
$this->db->where('Project.Deadline <',$eind);
}
$query = $this->db->get();
if($query->num_rows()>0){
return $query->result();
}
else{
return false;
}
}
The project.Begindatum and the Project.Deadline are varchar(10). So it looks at the first two numbers not the full date. For example:
$start = '01-04-2014';
'Project.Begindatum' = (Varchar)'02-03-2014'.
Then it will be shown because
it looks only to the '01'(-04-2014) and the '02'(-03-2014)

Use mysql's STR_TO_DATE() function and also pass third parameter in where() as FALSE
$this->db->where("STR_TO_DATE(Project.Begindatum,'%d-%m-%Y') >",$start,FALSE);
$this->db->where("STR_TO_DATE(Project.Deadline,'%d-%m-%Y') <",$eind,FALSE);
Its better to change the type of your columns to store in standard format use date type to store dates in database ,Using STR_TO_DATE with format %d-%m-%Y then the value stored in table should have %d-%m-%Y format otherwise it won't work ,it should be compared to $start = '2014-04-01';,otherwise you need another function i.e DATE_FORMAT to format it like 01-04-2014
$this->db->where("DATE_FORMAT(STR_TO_DATE(Project.Begindatum,'%d-%m-%Y'),'%d-%m-%Y') >",
$start,FALSE);
$this->db->where("DATE_FORMAT(STR_TO_DATE(Project.Deadline,'%d-%m-%Y'),'%d-%m-%Y') <"
,$eind,FALSE);

Reminder: STR_TO_DATE(...) output format: Y-m-d
Example: 2020-12-24
Therefore: $start and $eind format: Y-m-d
Example: 2020-12-31
$this->db->where("STR_TO_DATE(Project.Begindatum, '%m-%d-%Y') >",$start);
$this->db->where("STR_TO_DATE(Project.Deadline, '%m-%d-%Y') <",$eind);
I hope this helps you too. Peace.

Related

Yii2 Add math in where condition

In users table I have a column call "month".
I want to list all users that meet the condition: current month - user month <=2
Here my code
$time = new \DateTime('now');
$today = $time->format('m');
$users = Users::find()->where(['<=', 'month' - $today, 2])->all();
But this code is wrong. Please help me with this.
Hope this all make sense.
Thank you!
In Yii2 you can use different format for buil where condition
for this kind of situatio is useful use string format with param
in string format you can pass the literal string and param this way
$users = Users::find()->where('(month - :today ) <= 2' , [':today'=>$today])->all();
see this for more http://www.yiiframework.com/doc-2.0/yii-db-query.html#where()-detail

Codeigniter - Format date in WHERE clause

Is it possible to format the following date in an active record where clause?
I need to format channel_titles.entry_date to be in the format Y-m-d, like the $yesterday variable.
$yesterday = date('Y-m-d', strtotime('yesterday'));
$this->db->where('channel_titles.entry_date', $yesterday);
You can use DATE_FORMAT function like that:
$this->db->where("DATE_FORMAT(from_unixtime(channel_titles.entry_date), '%Y-%m-%d')", $yesterday, false);
Try this
$this->db->where("DATE_FORMAT(channel_titles.entry_date,'%Y-%m-%d') ", $yesterday);

PDO query does not return data when inserting date as variable

Im trying to get a hold of OOP and PDO. Did some tutorials. In the tutorial i got the query method (so thats not mine...)
but im having troubles with a pdo query
I want to select orders from the database matching a date..... de date comes from a datepicker and returns 2012-12-16 for example therefor
$dateInputQuery = date("Y-m-d", strtotime(Input::get('datepick')));
$data = $order->getAllOrders('order', 'WHERE DATE(orderdate) = DATE({$dateInputQuery})', false, false);
the strange thing is that when i replace the WHERE clause to WHERE DATE(orderdate) = \'2013-12-16\' it returns all the data but when inserting my date like above it does not....
in the db class the method looks like this
public function getAll($table, $where = NULL, $orderSort = NULL, $limit = NULL) {
$this->query("SELECT * FROM {$table} {$where} {$orderSort} {$limit}")->error();
return $this;
}
and query method in db class
public function query($sql, $params = array()) {
//reset error
$this->_error = false;
if ($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if (count($params)) {
foreach ($params as $param) {
$this->_query->bindValue($x,$param);
$x++;
}
}
if ($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
why is this ?
Your immediate problem is caused the fact that $dateInputQuery is unquoted. Date is a string literal and should be quoted. And even though you can easily add quotes around it you really shouldn't do this. See next point.
order is a reserved word in MySQL, therefore the table name should be put in backticks
$data = $order->getAllOrders('`order`', "WHERE DATE(orderdate) = DATE('$dateInputQuery')", false, false);
^ ^ ^ ^
You're not leveraging parameter binding in query() function. Instead on top of it you're using query string interpolation leaving your code vulnerable to sql injections and diminishing the usage of prepared statements. When you use parameter binding you no longer need to quote parameter values.
Your sql query is not index-friendly. You shouldn't apply any functions (in your case DATE()) to the column you're searching on (orderdate). Instead you can rewrite your condition to apply necessary transformations/calculations to the arguments which are constants.
You should avoid using SELECT *. Read Which is faster/best? SELECT * or SELECT column1, colum2, column3, etc and Why is using '*' to build a view bad?
That being said your query should look something like
$sql = "SELECT order_id, orderdate, ...
FROM `order`
WHERE orderdate >= ?
AND orderdate < ? + INTERVAL 1 DAY";
And you should execute it
$this->query($sql, array($dateInputQuery, $dateInputQuery));
Instead of passing whole clauses (e.g. WHERE) you should pass values

formatting date field from MYSQL

I am using a DATE field in my MYSQL table, and pulling it through on a php page. The problem is it comes out as "2011-04-23"
Is there a way I can reformat this as 23/04/2011?
Thanks :)
date("d/m/Y", strtotime("2011-04-23"));
that should do it
date()
strtotime()
DATE_FORMAT(date,format)
Look here: http://dev.mysql.com/doc/refman/5.0/es/date-and-time-functions.html
Assuming variable $date contains your MySQL data:
$date = '2011-04-23';
$timezone = 'Europe/London'; // this is optional argument
$formatted = DateTime::createFromFormat('Y-m-d', $date, new DateTimeZone($timezone));
// or without the optional timezone - where php will assume the default timezone from your OS
$formatted = DateTime::createFromFormat('Y-m-d', $date);
echo $formatted->('d/m/Y');

How to convert date in Text box to MySQL DATETIME format

I'm quite new to php and have been reading Larry Ullman book to develop a basic db site.
I have used the YUI Calendar pop up date picker to add a date to a text field called"date". The date format it enters is eg Thursday, 7 May 2009
I have tried many different ways to try and enter the date in to mysql db but it remains at 00 00 00 00 00 00
This is the code related to the date field I have,
// Check for a Date.
if (eregi ("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo '<p><font color="red">Please enter a valid Date!</font></p>';
}
// Add the URL to the urls table.
$query = "INSERT INTO urls (url, title, description, date) VALUES ('$u', '$t', '$d', '$p')";
$result = #mysql_query ($query); // Run the query.
$uid = #mysql_insert_id(); // Get the url ID.
if ($uid > 0) { // New URL has been added.
I think I have provided all pertinent information but again apologies if this isn't helpful and I will do my best to provide yo with any other information you may require.
Thanks - Sean
If the format that your date picker is passing in is "Thursday, 7 May 2009", then the strtotime() and date() functions should work to give you a valid date to pass to MySQL:
$p = date("Y-m-d H:i:s",strtotime('Thursday, 7 May 2009'));
If your database field is a DATE, you probably only want the "Y-m-d" part. If it's a DATETIME, you'll want the "H:i:s" as well.
You probably need to format the date in the way that mysql expects it for that datatype, or else it cannot recognize it. You could use a regex or similar method to extract the component parts and format it according to the format of the MySQL DATETIME type.
EDIT: See http://dev.mysql.com/doc/refman/5.0/en/datetime.html for said format. Also, you might be better off storing the date/time as a unix timestamp, as that usually is easier to maintain.
the date format in mysql is YYYY-MM-DD, so change the way you accept data on php
if (eregi ("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo 'Please enter a valid Date!';
Should be
if (eregi ("^([0-9]{4}/([0-9]{2})/([0-9]{2}))$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo 'Please enter a valid Date!';