MYSQL query using LIKE function for date - php

I have the following statement in the where statement of a mysql query:
WHERE scrap_date LIKE '%-01-%'
I want to grab all the data with the scrap_date being in January. The error I recieve is:
"Incorrect datetime value: '%-01-%' for column 'scrap_date' at row 1"
The datatype for scrap_date is DATETIME.
Not sure what syntax to use to get data with the a date in January, any suggestions?

You are assuming the date is represented internally as a string. It is not.
Since its a DateTime, use the MONTH function to extract the month and compare it to the desired value
WHERE MONTH(scrap_date) = 1

You may try this:
select * from your table WHERE MONTH(scrap_date) = 1

You can use the DATEPART() function
SELECT * FROM table
WHERE (DATEPART(mm, scrap_date) = 01)

use month function
WHERE MONTH(scrap_date) = 1

Related

mysql timestamp output as formatted Date not working

I have a crazy phenomenon in my php script. I have defined a column as a timestamp in a mysql table. I fill it with the function:
date("Y-m-d H:i:s");
The data in the table then look like this: 2017-04-19 17:08:45
When I query this column with mysqli as a unix timestamp again:
SELECT UNIX_TIMESTAMP (timestamp) as timestampUnix FROM posts
Then binding the result using bind_result to the variable $timestampUnix.
I can echo the variable with
echo $timestampUnix;
and it outputs a correct timestamp like this: 1492614559
however if i do the following:
$timestampUnix2 = $timestampUnix;
echo $timestampUnix2;
there is simply no echo output... What is the reason?
I tried this because I actually want echo only the date in an other format with:
date('d.m.Y', $timestampUnix)
and it gave me 01.01.1970 and i wondered why the timestamp must be 0 but it isnt since when i directly echo it it gives me a correct one.
however when i do
Date('d.m.Y', 1492614559)
it gives me the correct date.. no clue what is going on there!
i know there are many other questions about mysql php Date output, but no one have this issue as i think i cannot do something with the variable i got from the query.
thanks in advance!
edit: i attach the complete code in question:
---the query that inputs the data in the db----
$timestamp = date("Y-m-d H:i:s");
mysqli_query($mysqli,"INSERT INTO posts (timestamp)
VALUES ('$timestamp')");
---the query that fetches the data----
$results = $mysqli->prepare("SELECT UNIX_TIMESTAMP(timestamp) as timestampUnix FROM posts");
$results->execute(); //Execute prepared Query
$results->bind_result($timestampUnix); //bind variables to prepared statement
$postdate = date('d.m.Y',$timestampUnix)
echo $postdate;

Trying to make a stored Datetime value shorter with SQL Convert function

I'm new to using the convert function. I'm trying to make a datetime value from my table shorter. Currently my datetime values look something like this, 2016-10-14 16:51:41, but I'd like to make it look something like mm/dd/yy.
I don't know if this is the right approach (must not be since it doesn't work), but I've generated a query using the convert function and then fetching the data with a mysqli_fetch_array.
Here's the code I'm using:
$sql = "SELECT id, time, CONVERT(VARCHAR(11), time) as something FROM tableName";
$query = mysqli_query($db, $sql);
$statusnumrows = mysqli_num_rows($query);
// Gather data about parent pm's
if($statusnumrows > 0){
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$time= $row["time"];
}
}
Time is the name of the column which has the datetime type.
Thanks in advance, for suggestions/advice.
You should store datetime in your DB in proper data types like datetime etc.
As I can see you are using PHP, if you need to OUTPUT this datetime in some interface (f.e. HTML page), you should use PHP functions to convert date in format you need. That is the good practice
DB should STORE the data but formatting is front-end problem.
Simple example of strtotime() and date():
$Date = "2016-10-15";
$newDate = date("m/d/Y", strtotime($Date));
You can read docs on the PHP site: strtotime and date
If 2012+ you could use format (not very efficient but does offer some other possibilities)
Declare #Date DateTime = GetDate()
Select UsingFormat = Format(#Date,'MM/dd/yy')
,UsingConvert1 = convert(varchar(10),#Date,1)
,UsingConvert101 = convert(varchar(10),#Date,101)
Returns
UsingFormat UsingConvert1 UsingConvert101
10/15/16 10/15/16 10/15/2016
Use style 1 in Convert function for mm/dd/yy format
select CONVERT(VARCHAR(20), [time],1)
From yourtable
If you want mm/dd/yyyy format then use 101 style
select CONVERT(VARCHAR(20), [time],101)
From yourtable
MSDN link for Convert function with various style : CONVERT

MySQL PDO NOW() as assigned value - is it possible?

I'm trying to pass a MySQL's NOW() function into PDO's assigned value through PHP and it's failing. I found that I must pass this directly into MySQL statement. But in my case, sometimes the datetime field can be empty.
Is it even possible to pass NOW() as PHP's assigned value?
Some code:
I'm building query dynamically and the datetime is dependent on some other variable's value.
if(isset($accountStatus)&&$accountStatus!=""){
$tmp[':account_status']=$accountStatus;
if($accountStatus==0){
$tmp[':vCodeExpire']="NOW() + INTERVAL 1 WEEK";
$tmp[':verified']=0;
}else{
$tmp[':verified']=1;
}
}
Building SQL query:
$sql="";
foreach($tmp as $k=>$v){
$sql.=str_replace(":","",$k)."=".$k.",";
}
$sql=substr($sql,0,strlen($sql)-1);
Then, I run PDO query:
$db=$pdo->prepare("UPDATE users SET $sql WHERE id=:id");
$db->execute($tmp);
I tried replacing double-quotes with single-quote around NOW() + INTERVAL 1 WEEK with no luck.
I also tried with single-quote around PDO query, but then $sql is passed directly, not using an assigned values.
is it possible?
No.
There are 2 solutions.
Calculate expiration date using PHP. Something like date('Y-m-d',strtotime('+1 week'))
Create a conditional part for the query
if(isset($accountStatus)&&$accountStatus!=""){
$tmp[':account_status']=$accountStatus;
if($accountStatus==0){
$accSql = "NOW() + INTERVAL 1 WEEK,";
$tmp[':verified']=0;
}else{
$accSql ='';
$tmp[':verified']=1;
}
$db=$pdo->prepare("UPDATE users SET $accSql $sql WHERE id=:id");
Use strtotime() instead of MySQL to get date values.

update 2 record in different date?

I got a question regarding if I want update 2 record by only one command, isn't possible do like this ?
mysql_query("UPDATE damacaicheck SET trimresult = '$trim' where date = '$Current' and date = '$yesterdaydate'");
or
mysql_query("UPDATE damacaicheck SET trimresult = '$trim' where date in ('$Current','$yesterdaydate')");
Instead of date = '$Current' AND date = '$yesterdaydate'" use date = '$Current' OR date = '$yesterdaydate'"
Your first example needs to use OR rather than AND.
There was a no issue on your query problem is its may not return any value use OR instead of AND as previous posters said

How to grab items from a DB by date

This is my script:
$spending_period = time() - (30 * 24 * 60 * 60);
$spending_period = date('Y-m-d', $spending_period);
$monthly_income_query="SELECT amount FROM budget_items WHERE (date_code >= '$spending_period') && (type=='Income') ORDER BY date_code DESC";
$monthly_income_result=mysql_query($monthly_income_query);
while($monthly_income_scan=mysql_fetch_array($monthly_income_result)){
if($montly_income_counter >=1){
$monthly_income=$monthly_income + $monthly_income_scan['amount'];
}
}
I receive an error that mysql_fetch_array() is not a valid result resource.
The goal is to grab only items in the budget_items table that have a date_code (using the DATE type) occurring within the last 30 days.
Anyone have suggestions?
If something doesn't work with your
query - you may want to try it out in
mysql console with some sample date.
If data is returned, then try printing out a query. I have a hunch that $spending_period variable might not be interpolated correctly into your query string (try using '{$spending_period}' instead of '$spending_period'.
You need to format the date as a strong and use CAST inside the select statement to accept the value as a date value.

Categories