I have following php routine to extract values from a table. I'm trying to convert the DATE type from "2014-08-10", value to "20140810", value
Rtn:
//query
$query = mysql_query("SELECT CAST(date AS DATE), EtotalDay from MonthData group by 1 order by 1")
OR die ('Query is invalid: ' . mysql_error());
//write the results
while ($row = mysql_fetch_array($query)) {echo $row['CAST(date AS DATE)'] . "," . $row['EtotalDay'] . "\n";
Haw can I do this?
You should use
DATE_FORMAT(date, '%Y%m%d')
instead of CAST(), complete with an column alias name for the retrieving of the field
$query = mysql_query("SELECT DATE_FORMAT(date, '%Y%m%d') formattedDate, EtotalDay from MonthData group by 1 order by 1") or die ('Query is invalid: ' . mysql_error());
//write the results
while ($row = mysql_fetch_array($query)) {echo $row['formattedDate'] . "," . $row['EtotalDay'] . "\n";
see the manual, DATE_FORMAT
DATE_FORMAT(date,format)
Formats the date value according to the format string.
The following specifiers may be used in the format string. The “%”
character is required before format specifier characters.
%d Day of the month, numeric (00..31)
%m Month, numeric (00..12)
%Y Year, numeric, four digits
Related
I've broken down individual SQL queries for the information I want from my SQL table but I'm confused on how I can combine all statements agianst one variable. This variable is being used in PHP to display my data.
Here is the SQL queries I'm wanting to run.
SELECT * FROM weather ORDER BY stamp DESC LIMIT 1
SELECT SUM(rainfall) FROM weather WHERE stamp >= CURDATE()) AS total_rainfall
SELECT MAX(maxwind) FROM weather WHERE stamp >= CURDATE()) AS max_windspeed
SELECT MAX(temperature) FROM weather WHERE stamp >= CURDATE()) AS max_temperature
SELECT MIN(temperature) FROM weather WHERE stamp >= CURDATE()) AS min_temperature
Here is my current query which gives me everything I want except the max windspeed, max temperature, and minimum temperature for the last 24 hours.
SELECT *, (SELECT SUM(rainfall) FROM weather WHERE stamp >= CURDATE()) AS total_rainfall FROM weather ORDER BY stamp DESC LIMIT 1
Basically, I'm just wanting to add the maximum temperature, minimum temperature and maximum windspeed that occured within the current date.
MySQL data table example
Here is the way I'm trying to display the data using PHP.
<?php
$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 60; URL=$url1");
$connectinfo = mysql_connect("***", "***", "***")
or die(mysql_error());
mysql_select_db("raspberrydb001", $connectinfo);
$sql = "SELECT *, (SELECT SUM(rainfall) FROM weatherdata WHERE stamp >= CURDATE()) AS total_rainfall FROM weatherdata ORDER BY stamp DESC LIMIT 1; ";
$result = mysql_query($sql, $connectinfo);
while($row = mysql_fetch_array($result)) {
$windspeed = $row['windspeed'];
$maxwind = $row['maxwind'];
$temperature = $row['temperature'];
$humidity = $row['humidity'];
$rainfall = $row['rainfall'];
$stamp = $row['stamp'];
$d=mktime();
$total_rainfall = $row['total_rainfall'];
echo "<div style='text-align:center'><h5>Temperature: " . $temperature . "(F)" . "<br>" . "Rainfall: " . $total_rainfall . "(in)" . "<br>" . "Wind: " . $windspeed . "(MPH)" . "<br>" . "Humidity: " . $humidity . "(%)" . "<br>" . "</h5></div>";
echo "<div style='text-align:right'><h6>Updated at: " . $stamp . "</h6></div>";
echo "<br>";
}
?>
Thanks
I would propose to split it up into two queries.
First, to collect all your data:
SELECT * FROM weather ORDER BY stamp DESC LIMIT 1
Second, to collect the min/max data:
SELECT
SUM(rainfall) AS total_rainfall,
MAX(maxwind) AS max_windspeed,
MAX(temperature) AS max_temperature,
MIN(temperature) AS min_temperature
FROM
weather
WHERE stamp >= CURDATE())
LIMIT 1
'19/10/2013 2:41'
I have a huge dataset in the above format that I want to insert into my table. But I guess 'YYYY-MM-DD HH:MM:SS' is the format for datetime.
Any solutions?
You can use php preg_split() function.
<?php
$myDate = '19/10/2013 2:41';
$split = preg_split('/[\/\s]/',$myDate);
$formattedDate = $split[2] . '-' . $split[1] . '-' . $split[0] . ' ' . $split[3];
echo $formattedDate;
?>
Since your input is a string in the form 03.09.13, I'll assume (since today is September 31, 2014) that it's dd-mm-yy. You can convert it to a date using STR_TO_DATE:
STR_TO_DATE(myVal, '%d/%m/%y')
Then you can format it back to a string using DATE_FORMAT:
DATE_FORMAT(STR_TO_DATE(myVal, '%d/%m/%y'), '%Y-%m-%d')
Note that the year is %y (lowercase "y") in STR_TO_DATE and %Y (uppercase "Y") in DATE_FORMAT. The lowercase version is for two-digit years and the uppercase is for four-digit years.
I am using codeigniter's active record, but i've realized I probably need a regular SQL query for what I'm trying to accomplish. Could someone please look at this code and give me the correct format. What am I doing wrong here?
I think it's obvious what I'm trying to accomplish just by reading the code, but if you need more than just the syntax i've used (obviously in error), I'm happy to provide an explanation of code.
$today = date('Y-m-d H:i:s');
$where = "type == pk_card AND (end_date > $today OR qty >= 1)";
$this->db->select('id, title, pk_card_set, pk_card_number');
$this->db->from('auctions');
$this->db->where($where);
$this->db->like("CONCAT(title, ' ', pk_card_number, ' ', pk_card_set)", $keyword);
$query = $this->db->get();
There are number of mistakes in your code the way you are trying to query through active record
type == pk_card -> mysql if you want to compare any value against your column you need single = sign not double == correct one is type = 'pk_card'
type == pk_card ->Again if you want to compare any string value against column you need to wrap it with standard single quotes ' like type = 'pk_card'
end_date > $today if you want to compare date then again you need warp date string in single quotes like end_date > '$today'
And now you can write your active record query as below
$today = date('Y-m-d H:i:s');
$keyword='Test';
$where = "(end_date > '$today' OR qty >= 1)";
$this->db->select("id, title, pk_card_set, pk_card_number ");
$this->db->from('auctions');
$this->db->where($where,null,FALSE);
$this->db->where('type','pk_card');
$this->db->like("CONCAT(title, ' ', pk_card_number, ' ', pk_card_set)", $keyword);
$query = $this->db->get();
this will generate a query similar to
SELECT
`id`,
`title`,
`pk_card_set`,
`pk_card_number`
FROM
(`auctions`)
WHERE (
end_date > '2014-08-10 12:47:06'
OR qty >= 1
)
AND `type` = 'pk_card'
AND CONCAT(
title,
' ',
pk_card_number,
' ',
pk_card_set
) LIKE '%Test%'
Active Record
I hope that someone can tell me what I am doing wrong.
I would like to query my SQL table and receive back a ClassID and a ClassName.
The ClassID is a char(8) and holds values such as 123.45L1 or 350.12.
I am attempting to shorten that value so that I receive back 123 or 350 only.
Here is my code:
$classSelect = "SELECT LEFT(ClassID , 3), ClassName FROM Class GROUP BY ClassID";
$result = mysql_query($classSelect);
echo "<td><select multiple size='10' name='Class'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='Choice'" . $row['ClassID'] . " - " . $row['ClassName'] . "'>" . $row['ClassID'] . " - " . $row['ClassName'] . "</option>";
}
echo "</select></td>";
SELECT LEFT(ClassID , 3) AS somename, ClassName
and then refer it from PHP as $row['somename']
If you are seeking to extract the string up to the decimal point, and that might not always be in the same place, you can use MySQL's SUBSTRING_INDEX() function:
SELECT SUBSTRING_INDEX(ClassID, '.', 1) FROM Class
If you are seeking to extract the integer up to the first non-decimal character, you can simply CAST() the string and MySQL will do the rest:
SELECT CAST(ClassID AS UNSIGNED) FROM Class
The benefit of this latter approach is that the resulting column will be of the correct datatype.
My requirement is to pull records from mysql database which have just 5 mins left from the current time as per the one of the columns in the database. The column is has user inserted datetime.
date_default_timezone_set("UTC");
$utc_time = date("Y-m-d H:i:s", time());
echo "UTC Time: " . $utc_time . "<br>";
$result = mysql_query("select reminder_text, reminder_subject, reminder_date_time_utc $table_name where (TIME_TO_SEC (TIMEDIFF(reminder_date_time_utc , '$utc_time')) < 300) AND (TIMEDIFF(reminder_date_time_utc , '$utc_time')) > 0) ") or die(mysql_error());
here the reminder_date_time inside the TIMEDIFF function is the column name to pick up the DATETIME. Using this query I do not get the results but if I place the date instead of reminder_date_time it gives me the correct output. For example if I say TIMEDIFF('2013-07-12 11:05:00' , '$utc_time') it gives me the correct output. And this same value: 2013-07-12 11:05:00 is actually present in one of the rows of this column reminder_date_time_utc
Any advice where I am going wrong... Does TIMEDIFF function not accept column name as one of the parameters.
Do you forgot the FROM in your sql?
Why dont you try to do it like following:
$utc_time = date("Y-m-d H:i:s", time() - 30000);
and change the query to
'SELECT * FROM ' . $tablename . ' WHERE reminder_date_time_utc > "' . $utc_time . '"';
or use DATE_ADD() function :
'SELECT * FROM ' . $tablename . ' WHERE reminder_date_time_utc > DATE_ADD(NOW(), INTERVAL -'5' SECOND));