I have a database of records that have a timestamp asscoiated with them. I would like to pull records from the database grouped by day, so if there are other records with the same date (24 hour span) I would like them to be grouped together. Can this be done with MYSQL or will I have to pull the records and organise them into arrays using PHP?
Here is a screenshot of my table:
Here is my model function so far:
public function getUsersMoves($options) {
$query = "SELECT * FROM myzone_user_hr_records";
if(isset($options['GUID'])) {
$query .= " WHERE GUID = '" . $options['GUID'] . "'";
}
if((isset($options['minHR'])) && isset($options['maxHR'])) {
$query .= " AND (hr BETWEEN '" . (int)$options['minHR'] . "' AND '" . (int)$options['maxHR'] . "')";
} else if (isset($options['zone'])) {
$query .= " AND zone = '" . (int)$options['zone'] . "'";
}
if(isset($options['activity'])) {
$query .= " AND title = '" . $options['activity'] . "'";
}
$query .= " ORDER BY time DESC";
$query = $this->db->query($query);
return $query->result_array();
}
And my controller code:
$moves = $this->myzone_model->getUsersMoves($options);
I want the data sorted so that these records are grouped together if they have the same date in the timestamp, for example (2012-11-20).
Thanks
try this :
SELECT *, DATE(time) AS date FROM [whatever you want] GROUP BY date
select * from TABLE where `time` like '2012-11-20%'
The option I have suggested works because the LIKE condition in the WHERE selects all dates from the time field that start with 2012-11-20. That means that it doesn't matter what time it is during the day, it will return all results for that day.
To make this work, you must remember to use LIKE and then add the wildcard at the end - %. You can also add the wildcard at the beginning if you wanted. An example to return all days (11th December) for multiple years would be:
SELECT * FROM TABLE WHERE `time` like '%-12-11%'
Related
I have a table in Database PhpMyAdmin with certain values, and I want to UPDATE only ONE value of these, WHERE the latest initial_date (TIMESTAMP) is.
I write down here the code I generated as an example, so you can see I actually obtain that date value through SELECT, but I don't manage to UPDATE it. Thank you very much.
$select = "SELECT MAX(initial_date) AS max_value FROM services WHERE matricula = '" . $_POST["taxi"] . "'";
$select_results = mysqli_query($conexion, $select);
while($row = mysqli_fetch_array($select_results)){
echo $row['max_value'];
$update_carrera = "UPDATE services SET";
$update_carrera .= " costo_carrera = costo_carrera + " . $_POST["costo_carrera"] . ",";
$update_carrera .= " final_date = CURRENT_TIMESTAMP";
$update_carrera .= " WHERE initial_date = ''";
$update_carrera_results = mysqli_query($conexion, $update_carrera);
}
I leave WHERE initial_date = '' empty so you can tell what should it be. I get a correct date value in the echo $row['max_value']; if I solve the WHERE with a WHERE initial_date = '20160405153315' (INTEGER), but I don't want to put myself the integer, of course I want to get the newest date from the table database.
I would like to start from an example: you received some list with needed fields. This list may vary and even if it is empty, select all fields. This list can include fields from several tables. Is there any way to generate SELECT query for doing this?
Probably there is a way, but it will look like parsing received list, adding appropriate table alias, and then adding modified list into select clause. Is it best way actually?
Update 1
The goal is only to get passed fields from several tables, not to
control result from any of them(its about first answer)
You could create a query that first selects dynamically fields, depending on your criteria.
for example lets assume you have two criteria passed to you. Then (after you have made sure your criteria1 and criteria2 are safe):
$mySelect = ''; //placeholder so that you can add select fields
$extraTables = ''; //placeholder to put the extra tables I may need
$criteria = " WHERE 1 "; //this will select everything
if ($criteria1>'') {
$mySelect .= ' , t3.field3 ';
$extraTables = " , aDifferentTable AS t3";
$criteria .= " AND t3.someKey = t1.someKey '";
$criteria .= " AND field_crit1 = '" . $criteria1 . "'";
}
//and an example of connecting dynamically to an other table
if ($criteria2>'') {
$mySelect .= ' , t2.field5 ';
$extraTables = " , anOtherTable AS t2";
$criteria .= " AND t2.someKey = t1.someKey '";
$criteria .= " AND t2.field_crit2 = '" . $criteria2 . "'";
}
//lets combine all together into one dynamically created query
$myquery = "SELECT t1.something " . $mySelect . " FROM myTable AS t1";
$myquery = $myqury . $extraTables . $criteria;
My table in mysql has special data stamp (startdata). It is date when event starts. Older events stored in database to, but i don't need them to appear in the MySQL answer.
So is there any way sending query to database that includes parameter i need? (for example, not showing rows where startdate older than today).
Now my code looks like:
$res3 = mysqli_query($con,"SELECT * FROM raspisanie WHERE
instr='" . $instrument . "' AND school IN(" . $array2 . ")
AND type='regular' AND state='1' ORDER by startdate");
Add condition in your where clause.
$res3 = mysqli_query($con,"SELECT * FROM raspisanie WHERE
instr='" . $instrument . "' AND school IN(" . $array2 . ")
AND type='regular' AND state='1' AND startdate >now() ORDER by startdate");
I'm guessing that I'm just a little rusty or something because it seems like this should be working. Am I missing something here...
Here is the code I am trying to use...
<?php
echo dbConn();
$existing_time = mysql_result(mysql_query("SELECT p_time FROM scores WHERE p_uid=$uid"), 0);
$existing_category = mysql_result(mysql_query("SELECT p_cat FROM scores WHERE p_uid=$uid AND p_cat=$pieces"), 0);
if ($existing_category == "") {
mysql_query(
"INSERT INTO scores VALUES (
'',
'$uid',
'$pusername',
'$time',
'$pieces'
)");
} elseif ($existing_time <= $time) {
echo "No Change! Old Score Was Better (Lower)";
} elseif ($existing_time > $time) {
mysql_query("UPDATE scores SET p_time = " . $time . " WHERE p_uid = " . $uid . " AND p_cat = " . $pieces . "");
};
?>
Now... Here is what I am trying to do...
I am collecting info from the database where the users username AND category match. If the category for that user does not exist, it inserts the latest score. (This much works.)
Then, if the category does exist but the old score is better, it just does nothing. (This part works too)...
However, what I can't seem to do is get it to update the last score, if the current score is better (lower score, since this is a time based game.) It doesn't update the score.
I am trying it this way: By updating a row in "scores" where the USERNAME and the CATEGORY match at the same time.
Please note... where it says "pieces". this is a category. Where it says "time", this is a score. The score is returned as 00:00:00 for hours minutes and seconds.
EXAMPLE: (in parentheses is the database row name)
id (ID) = just KEY id in sequencial order
user id (p_uid) = 123456789
username (p_username) = somename
score (p_time) = 00:01:03
category (p_cat) = 10
Change you update statement to:
mysql_query("UPDATE scores SET p_time = '" . $time . "' WHERE p_uid = " . $uid . " AND p_cat = " . $pieces . "");
You have missed quotes in the update statement around $time.
I want to count a record by current date from different tables and return as one row with different column in the new table. The code will update a record every three hours and insert new record if current date changes. I've current date and time data (2013-05-20 14:12:12) in "created_at" column. Here my current code:
require_once('./db_connect.php');
$dbcon = new db;
//test to see if a specific field value is already in the DB
public function in_table($table,$where) {
$query = 'SELECT * FROM ' . $table . ' WHERE ' . $where;
$result = mysqli_query($this->dbh,$query);
$this->error_test('in_table',$query);
return mysqli_num_rows($result) > 0;
}
//running in background
while (true) {
$select= "SELECT (SELECT CURDATE()) AS time," .
"(SELECT COUNT(tweet_id) FROM tweets WHERE created_at= 'CURDATE() %') AS total_count," .
"(SELECT COUNT(fid) FROM fun WHERE ftime= 'CURDATE() %') AS f_count," .
"(SELECT COUNT(sid) FROM sad WHERE stime= 'CURDATE() %') AS s_count";
$results = mysqli_query( $dbcon, $select );
while($row = mysqli_fetch_assoc($result)) {
$time = $row['time'];
$total = $row['total_count'];
$fcount = $row['f_count'];
$scount = $row['s_count'];
$field_values = 'time = "' . $time . '", ' . 'total_count = ' . $total . ', ' . 'fun_count = ' . $fcount . ', ' . 'sad_count = ' . $scount;
if ($dbcon->in_table('count','time= "' . $time . '"')) {
$update = "UPDATE count SET $field_values WHEN time= '$time'";
mysqli_query( $dbcon, $update );
}
else {
$insert = "INSERT INTO count SET $field_values";
mysqli_query( $dbcon, $insert );
}
}
//update record every 3 hour
sleep(10800);
}
With this code I can't get a count record. The result return | 2013-05-18 | 0 | 0 | 0 |. How can I correct this?
I not familiar with PHP, but you can retrieve the count of all records dated any time today using:
SELECT COUNT(tweet_id)
FROM tweets
WHERE created_at >= curDate()
AND created_at < date_add(curDate(), interval 1 day)
It is equivalent to saying
..
WHERE created_at >= (today at midnight *incusive*)
AND created_at < (tomorrow at midnight *exclusive*)
Update:
The advantage of this method is it is index friendly. While using WHERE DATE(Column) = currDate() works, it can prevent the database from using indexes on that column, making the query slower.
Replace the parts where you have this:
WHERE created_at= 'CURDATE() %'
with this:
WHERE DATE(created_at) = CURDATE()
Your existing WHERE clause is comparing created_at to the string constant CURDATE() %, and they'll never match.
You are comparing against created_at= 'CURDATE() %', which is looking for that exact string, not for the result of a function. If the field created_at is a date, it will never match.
And, you are doing that for all counts.