Retrieving a particular column value from multiple data rows PHP/MySQL - php

I trying to put a query together which echo/prints one particular column value from within the table, but within a particular time frame but I'm not having much luck. From the Query below, Im trying to get the '267' in the targets_id=1 row under the targets_set column to echo/print. I get the error message "mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource ". How do I get it to echo?
<?php
$dealer = $_SESSION['sp_dealer_code'];
require_once ('/database.php');
$result = mysql_query("SELECT targets_set FROM targets WHERE targets_nmc='F80', sp_dealer_code=$dealer AND `targets_date`
BETWEEN '2014-01-01 00:00:00' AND '2014-01-31 23:59:59' LIMIT 1");
$row = mysql_fetch_assoc($result);
echo $row['targets_set'];
?>
The Database table 'targets' and some sample data
targets_id | sp_dealer_code | targets_nmc | targets_set | targets_actual | targets_date
1 | 1234 | F80 | 267 | 270 | 2014-01-01 01:00:00
2 | 1234 | F8R | 350 | 300 | 2014-02-01 01:00:00
3 | 4567 | F80 | 210 | 200 | 2014-03-01 01:00:00
4 | 4567 | F8R | 267 | 260 | 2014-01-01 01:00:00

Your query is off. WHERE A, B AND C is not valid MySQL; rather, it should be WHERE A AND B AND C:
SELECT targets_set
FROM targets
WHERE
targets_nmc='F80'
AND sp_dealer_code=$dealer
AND `targets_date` BETWEEN '2014-01-01 00:00:00' AND '2014-01-31 23:59:59'
LIMIT 1
When the statement is executed, no result set is given back. That's why you get that error message when you try to fetch the result as an associative array.

Related

Eloquent get last record groupped by date

I have a table prices with where I store more times in a day more values referred to a customer like this:
Table prices:
| id | customer_id | value_1 | value_2 | value_3 | created_at |
-------------------------------------------------------------------------
| 1 | 10 | 12345 | 122 | 10 | 2021-08-11 10:12:40 |
| 2 | 10 | 22222 | 222 | 22 | 2021-08-11 23:56:20 |
| 3 | 12 | 44444 | 444 | 44 | 2021-08-12 08:12:10 |
| 4 | 10 | 55555 | 555 | 55 | 2021-08-13 14:11:20 |
| 5 | 10 | 66666 | 666 | 66 | 2021-08-13 15:15:30 |
| 6 | 10 | 77777 | 777 | 77 | 2021-08-13 16:12:50 |
I have some filters on that table to retrieve only records with date greater than X and/or lower than Y, sort records by value_1 or value_2, etc...
With that filters I have to take only 1 record for each day of a customer specified.
I'm able to get the record with the highest value_1 for example, by using sql function max() and group by date.
// Init query
$query = Price::query();
// Take the greatest value of value1
$query = $query->selectRaw(
'max(value_1) as highest_value_1, ' .
'date(created_at) as date'
);
// If defined, add a greater or equals
if ($from) $query->where("created_at", ">=", $from);
// If defined add a lower or equals
if ($to) $query->where("created_at", "<=", $to);
// Get results for current customer only, grupping by date and ordering it
$query = $query->where('customer_id', $id)->groupBy('date')
->orderBy('date', 'DESC');
// Fetch records
$records = $query->get();
But now I would like to have only the last record for each day of a customer specified.
I need an eloquent/sql solution because the date range to search may be large and the table has a lot of records.
How can I archive that?
Thanks
Not a complete solution (no customer filter nor laravel use), but I would use something like that in pure sql :
SELECT
CONCAT(EXTRACT(YEAR_MONTH FROM created_at),EXTRACT(DAY FROM created_at)) AS day,
MAX(created_at)
FROM mytable
GROUP BY day;
Of course, you may use other function to group by day (like string regexp or substr).

Query MySQL count data & turn into JSON

My table contains a column of 'datetimes', with an id.
+----+---------------------+
| id | datetime |
+----+---------------------+
| 0 | 2016-09-02 12:13:13 |
| 1 | 2016-09-02 10:16:11 |
| 2 | 2016-09-05 11:03:23 |
| 3 | 2016-09-08 11:34:45 |
| 4 | 2016-09-08 09:23:06 |
| 5 | 2016-09-08 10:22:05 |
| .. | ... |
+----+---------------------+
There will be multiple instances of each date in the table. My aim is to gather the amount of times each date occurs. So for the table above:
2016-09-02 => 2
2016-09-05 => 1
2016-09-08 => 3
I then need to move the data into JSON format using PHP like so:
[{"date":"2016-09-02","count":"2"},
{"date":"2016-09-05","count":"1"},
{"date":"2016-09-08","count":"3"}]
The JSON format will be used by a d3.js script I have written to plot each date against the frequency each date occurs.
I have never dealt with this kind of query before so I really have no idea where to start, or how to use PHP to move into JSON format. Thank you to anyone that can help.
Use the following query:
SELECT DATE_FORMAT(datetime, '%Y-%m-%d') AS `date`,
COUNT(*) AS `count`
FROM yourTable
GROUP BY DATE_FORMAT(datetime, '%Y-%m-%d')
Then create the JSON in your PHP code:
$a = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$a[] = array('date' => "$row['date']", 'count' => "$row['count']");
}
$json = json_encode($a);
I think below SQL useful to you. please run and see
SELECT DATE_FORMAT(datetime, '%Y-%m-%d'),count(*)
FROM yourTable
GROUP BY 1
order by 1

MySql AVG() and WHERE

I'm struggling on how to write this query and cant quite find an answer to help me with my case.
Consider the following table:
-----------------------------------------------
| ID | Value1 | Value2 | Value3 | Date |
-----------------------------------------------
| 1 | 10 | 23 | 30 | 2015-01-01 |
-----------------------------------------------
| 1 | 11 | 33 | 40 | 2015-02-01 |
-----------------------------------------------
| 2 | 26 | 93 | 20 | 2015-01-01 |
-----------------------------------------------
| 2 | 11 | 33 | 50 | 2015-02-01 |
-----------------------------------------------
I want to retrieve the average value of Value1 where the Date is 2015-01-01
I thought that
SELECT AVG(PAM_1) FROM MyTable WHERE DATE = 2015-01-01
would work but of course it does not. I'm aware that I probably need to use HAVING but I'm being confused if I must also use GROUP BY and if do I need the AS (something) part.
EDIT
The problem was not related to the query. I was supplying the date trough a variable as such:
$sth = $db->prepare("SELECT AVG(Value1) FROM MyTable WHERE DATE = $date");
Which is not possible to do with prepared statements.
Your query is basically fine. Your date constant is not. Dates constants should be enclosed in single quotes:
SELECT AVG(PAM_1)
FROM MyTable
WHERE DATE = '2015-01-01';
If the date could have a time component, then the following is the best way to handle this:
SELECT AVG(PAM_1)
FROM MyTable
WHERE DATE >= '2015-01-01' AND DATE < '2015-01-02';

Querying MySQL Timestamp in PHP

I'm querying the timestamp from the field created in the table messages.
My database table currently stands as..
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| msg_id | messages | uid_fk | ip | created | uploads |
| 706 | ........ | 39 | .. | 1368631445 | 0 |
| 717 | ........ | 39 | .. | 1368640802 | 0 |
| 705 | ........ | 39 | .. | 1368631238 | 0 |
| 696 | ........ | 39 | .. | 1368595705 | 0 |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
This is how I'm querying the timestamp from created.
public function Time_Stamp($uid){
$res = mysql_query("SELECT created FROM messages WHERE uid_fk='$uid'");
while ( $row = mysql_fetch_array($res) ) {
echo date("g:i", strtotime($row["created"])) . "<br />";
}
}
----- Output -----
9:00
9:00
9:00
9:00
So basically just printing out in a list the same time.
It's not printing their unique time from the created field. I'm not so perfect with MySQL but It has do to with their unique iD's(either msg_id, uid_fk) also, $uid equals the uid_fk, $uid is defined in another table.
How do I go about bringing their specific iD's to print out their correct timestamp.
echo date("g:i", $row["created"]);
strtotime turns a date string like 2013-05-15 22:35:00 into a timestamp.
date turns a timestamp into a readable date string.
You already have timestamps in the database, don't use strtotime.

select latest element from mysql table

I need to write a query to retrieve values from two columns using mysql table
My table has the following strucutre
| ID | user_id | datetime | message |
| 1 | 21 | 2012-05-10 04:13:01 | message1 |
| 2 | 07 | 2012-05-10 04:17:51 | message2 |
| 3 | 21 | 2012-05-11 04:21:51 | message3 |
| 4 | 21 | 2012-05-11 04:43:51 | message4 |
| 5 | 07 | 2012-05-11 04:21:51 | message5 |
| 5 | 21 | 2012-05-11 04:43:51 | message6 |
i wrote the below query
$query="SELECT MAX(datetime) FROM messages where user_id=21 and date=2012-05-11";
but i am not getting latest record from table iam getting null value
help us
$query="SELECT MAX(datetime) FROM messages where user_id=21 and date LIKE '2012-05-11%'";
You should use DATE(date) to get date of timestamp. MySQL function DATE() extracts only date without hours, minutes and seconds.
Here is your query:
SELECT MAX(datetime)
FROM messages
WHERE user_id = 21 AND DATE(date) = '2012-05-11'
Have you tried the following?
$query="SELECT MAX(datetime) FROM messages where user_id=21";
Update:
In your question, you didn't specify if you wanted to retrieve last record for a certain date. If you do, you'd need to use MySQL's date function.
Are you looking for the most recent record? You can get this with a subquery:
$query = "SELECT * FROM messages WHERE datetime = (SELECT MAX(datetime) FROM messages)";
Your query asks for ".....date=2012-05-11";" but your table does not have the field named date? did you mean datetime? if so, you may want to try ".....datetime like '2012-05-11%'";

Categories