Use the result of one Mysql command in Another Mysql Command? - php

Excuse my ignorance but I'm having a tough time figuring this out.
I'm trying to take the result from one mysql command, and use it in another command.
Here's my code, it doesnt work.
//select the event end date of event ID
$sql = "SELECT enddate FROM mm_eventlist_dates WHERE id = $id";
$result = mysql_query($sql);
//plug in the event end date, find event that starts the next day
$sql = "SELECT id FROM mm_eventlist_dates WHERE startdate = date_add($result, INTERVAL 1 DAY)";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo "Next Event ID" . $row['id'];
I'm so lost.
Please help!
Thanks, Nick

If I understand what you're trying to accomplish, it looks like you want to find all the events that start the day after a given event. Correct? In that case, what you want to do is a self-join, that is, join a table to itself. You need to give at least one occurrence of the table an alias so SQL can tell them apart.
So maybe something like this:
SELECT e2.id
FROM mm_eventlist_dates e1
join mm_eventlist_dates e2 on e2.startdate = date_add(e1.enddate, INTERVAL 1 DAY)
where e1.id=$id

Is there a reason that you can't combine them in to one query?
SELECT m1.id FROM mm_eventlist_dates m1
JOIN mm_eventlist_dates m2 ON m1.startdate = date_add(m2.enddate, INTERVAL 1 DAY)
WHERE m2.id = $id

mysql_query() returns a result set, not an actual database item. To do what you want above, do something similar to this (doesn't include error checking etc):
//select the event end date of event ID
$sql = "SELECT enddate FROM mm_eventlist_dates WHERE id = $id";
$result = mysql_query($sql);
$enddateRow = mysql_fetch_array($result);
//plug in the event end date, find event that starts the next day
$sql = "SELECT id FROM mm_eventlist_dates WHERE startdate = date_add('" . $enddateRow["enddate"] . "', INTERVAL 1 DAY)";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo "Next Event ID" . $row['id'];

You cannot use $result directly in date_add. Call mysql_fetch_array (as you do a few lines later), and use $row['enddate'].

//select the event end date of event ID
$sql = "SELECT enddate FROM mm_eventlist_dates WHERE id = $id";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$enddate = $row['enddate'];
//plug in the event end date, find event that starts the next day
$sql = "SELECT id FROM mm_eventlist_dates WHERE startdate = date_add($enddate, INTERVAL 1 DAY)";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo "Next Event ID" . $row['id'];
I think

You can not use the result of mysql_query directly in another query, you need to fetch the value first.
Instead of
$result = mysql_query($sql);
//plug in the event end date, find event that starts the next day
$sql = "SELECT id FROM mm_eventlist_dates WHERE startdate = date_add($result, INTERVAL 1 DAY)";
Try
$result = mysql_query($sql);
$enddate = mysql_fetch_assoc($result);
//plug in the event end date, find event that starts the next day
$sql = "SELECT id FROM mm_eventlist_dates WHERE startdate = date_add($enddate, INTERVAL 1 DAY)";

try this
//select the event end date of event ID
$sql = "SELECT enddate FROM mm_eventlist_dates WHERE id = $id";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result)
//plug in the event end date, find event that starts the next day
$sql = "SELECT id FROM mm_eventlist_dates WHERE startdate = date_add(".$row['enddate'].", INTERVAL 1 DAY)";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo "Next Event ID" . $row['id'];

Related

Loop Through Array and Echo Next Event

I have events stored in mysql that I retrieve with php. I retrieve the month, day, and year, then I add it to an array. Is there a way to loop through that array and grab the next upcoming event?
$array = [''];
$result = mysqli_query($con,"SELECT * FROM events") or die ("couldn't fetch query");
// output data of each row
while($row = mysqli_fetch_array($result)) {
$date = $row['eMonth'] . "-" . $row['eDay'] . "-" . $row['eYear'];
array_push($array, $date);
}
create a date column for each event and use this query to select next 3 events from current date
SELECT *
FROM EVENTS
WHERE event_date >= CURDATE() ORDER BY event_date ASC LIMIT 3;

how to run a query as long as another day with specific data found

Maybe it sounds crazy, but I couldn't come up with a better title.
I click a button and I send a date (Y-m-d) to a query, which looks up if data found and if data is found, it gives me the data back, if no data found, then it returns null.
Now I would like to do it so, that if no data available for the date I sent, the next date will be returned where data actually exists.
So practically I send a search for 30 August and if no data available for 30 August, the query should search for the next day in THE PAST for available data, so if it finds data on the 2nd August, then the data of 2nd August should be returned.
I tried with "date <= actual date" and "if result == 0" etc. but I am just tapping in the dark.
The return is always a bunch of data, not just a single row.
My code looks like this now:
$category = $_GET['category'];
$query = mysqli_query($bd, "SELECT MAX(datum) as max_datum, MIN(datum) as min_datum FROM macapps WHERE free = 1 AND category = '".$category."' ") or die(mysqli_error());
$date = mysqli_fetch_assoc($query);
$day = isset($_GET['date']) ? $_GET['date'] : 0;
$date = date('Y-m-d', strtotime($date['max_datum'] . ' ' . $day . ' day'));
$result = mysqli_query($bd, "SELECT appID, title, icon, category, datum FROM macapps WHERE datum = '".$date."' AND free = 1 AND category = '".$category."' ORDER BY title") or die(mysqli_error());
$rows = array();
while($count = mysqli_fetch_assoc($result)) {
$rows[] = $count;
}
echo json_encode($rows);
Try this query
Select
appID, title, icon, category, datum
From
macapps
Where datum = (Select
m.datum
From
macapps m
WHERE
m.datum <= '.$date.'
Order By m.datum Desc
LIMIT 1
)
And
Free=1
And
category = '.$category.'
Order By title;
Another Query
Select
appID, title, icon, category, datum
From
macapps
Where datum = (Select
Max(m.datum)
From
macapps m
Where
m.datum <= '.$date.'
)
And
Free=1
And
category = '.$category.'
Order By title

php mysql today's sum and monthly sum

I am trying to calculate the total of today's sales but this doesn't work.
It works, if I remove the date part...
# This works and will gives out the total:
$result = mysql_query("SELECT SUM(grand_total) AS value_sum FROM order");
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
# This doesn't work:
$result = mysql_query("SELECT SUM(grand_total) AS value_sum FROM new_order WHERE date = CURDATE()");
$query = mysql_query($result) or die ('Error: ' . mysql_error());
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
Also, how can I get the monthly total of this column after this?
If date field is DATETIME type, then try this sql statement:
SELECT SUM(`grand_total`) AS value_sum
FROM `order`
WHERE DATE(`date`) = CURDATE()

mysql check if uid record exist for today based on timestamp else do an insert

Im trying to do a mysql check if a record from $uid exist from today based on $timestamp and if it doesnt then do an INSERT.
//EXAMPLE RECORD FROM TABLE VOTE
--- #vote_fb_uid# --- #vote_time#
665414807 1369219044
tjt
//STEP 1 - do a look up on $uid and check with timestamp $today
$timestamp = $this->time;
$date = date('Y-m-d', $timestamp);
$today = date('Y-m-d');
$sql = "
SELECT * FROM vote WHERE
vote_fb_uid = '$this->fb_uid',
WHERE vote_time = '$CHECK_IF_THERE_IS_AN_ENTRY_FROM_TODAY'";
$res = mysql_query($sql) or die( mysql_error());
//STEP 2 - If no records are found for today - then we do an INSERT
if($no_record_for_today) {
$sql = sprintf("
INSERT INTO vote(
vote_fb_uid,
vote_time)
VALUES ('%s','%s')",
mysql_real_escape_string($this->fb_uid),
mysql_real_escape_string($this->time));
$res = mysql_query($sql) or die( mysql_error());
}
Obviously im strugling with the SQL part for the look up - im wondering if there isnt some in-built SQL function to do this or similar?
to check if you had a vote in the last 24 hours :
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND FROM_UNIXTIME(vote_time) >= DATE_SUB(NOW(), INTERVAL 1 DAY)
if you want to limit to the same day (mean you are allowed to post at 2013.05.21 23:55 and 2013.05.22 00:05)
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND DATE(FROM_UNIXTIME(vote_time)) = DATE(NOW())
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.
mysql> SELECT CURDATE();
-> '2008-06-13'
mysql> SELECT CURDATE() + 0;
-> 20080613
Try this:
$today = date('Y-m-d'); //change it to timestamp if you want in timestamp
$sql = "
SELECT count(*) as total FROM vote WHERE
vote_fb_uid = '$this->fb_uid' and
vote_time = '$today'";
$res = mysql_query($sql) or die( mysql_error());
if($res[0]['total'] < 1){
$sql = sprintf("
INSERT INTO vote(
vote_fb_uid,
vote_time)
VALUES ('%s','%s')",
mysql_real_escape_string($this->fb_uid),
mysql_real_escape_string($this->time));
$res = mysql_query($sql) or die( mysql_error());
} else{
//return error("custom","","Already Inserted.");
echo "already inserted";
}
Your $sql query have a syntax error, you have used two times clause WHERE the correct syntax to use two or more clauses in where is using AND to join them, to get only record wich don't have an entry for today you can use DATE_SUB with 1 day interval
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid',
AND vote_time <= DATE_SUB(vote_time, INTERVAL 1 DAY)

Prevent repetitive rows

I have this table :
I would like to delete same rows. For example first five rows are the same, my table should have only one row that includes this data : 40.792274 29.412994 2011-12-21 17:19:52.
So I used the following code :
$query = "SELECT * FROM table GROUP BY date";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$date = $row['date'];
$lat = $row['latitude'];
$lon = $row['longitude'];
$query = "SELECT * FROM table WHERE date='$date' AND latitude='$lat' AND longitude='$lon'";
$re = mysql_query($query);
$number = mysql_num_rows($re);
$number--;
$query = "DELETE * FROM table WHERE date='$date' AND latitude='$lat' AND longitude='$lon' LIMIT $number";
mysql_query($query);
}
But this code doesn't work.. What should I do ?
Edited :
I solved my question :
$query = "SELECT * FROM table GROUP BY date";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$date = $row['date'];
$lat = $row['latitude'];
$lon = $row['longitude'];
$query = "SELECT * FROM table WHERE date='$date' AND latitude=$lat AND longitude=$lon";
$re = mysql_query($query);
$number = mysql_num_rows($re);
$number--;
$query = "DELETE FROM table WHERE date='$date' AND latitude=$lat AND longitude=$lon LIMIT $number";
mysql_query($query);
}
Query lines were incorrect in my first question.
To remove the duplicate elements, you would use something like this:
$q = "SELECT date FROM table GROUP BY date"
$r = mysql_query($r);
$date = '';
while($row = mysql_fetch_array($r)){
$date = $row['date'];
$q = "SELECT date FROM mytable WHERE date='$date'";
$re = mysql_query($q);
$num = mysql_num_rows($re);
$num--;
$q = "DROP FROM mytable WHERE date='$date' LIMIT $num";
mysql_query($q);
}
Should do the trick. More specifically, when creating your $date value, you have to provide PHP with a time to use. date() defaults to using the current time, but you can provide it with a custom time as the second argument.
I suggest you take a look at the strtotime() manual at php.net as well (To translate times in your db to timestamps that can be used with date() ).
EDIT: The Answer above has been edited to remove all duplicate entries.
Try changing $dateOfNewData = date('Y-m-d H:i:s');
to
$dateOfNewData = date('Y-m-d 00:00:00'); //or change the first 00 to H if you need it to match by hour, second 00 to i if you need to match minutes and the same with seconds.
or $dateOfNewData = date('Y-m-d') which is pretty much the same and works with datetime field types
And you also need to modify your query to something like this unless you need an exact time:
"SELECT * FROM mytable WHERE date = '$dateOfNewData'" // you might also want the end date if you're working with the past in your database.
Well you can try like "Ignas" suggest but you cal also try this:
First just get the date (year, month, day) without hour, minutes and seconds. If you use full date format then you need to match exactly the same time. (to second the same) which is not really what you are looking for i guess. So you can use this:
$dateOfNewData = date('Y-m-d'); //just get year, month, day in right format (2011-12-20)
Then run a query. Here you have more options but i think the easier is something like that:
"SELECT * FROM mytable WHERE date_col LIKE '$dateOfNewData%' GROUP BY date_col"
This will group the same dates together and will display just once and will match all the rows where 'date_col starts with example: 2011-12-20% (thats why i use LIKE and $dateOfNewData%)
$dateOfNewData contains current date in this format:year-month-day (2011-12-20) and in Mysql query dont forget to use % at the end of the date. It's like * in windows for example.
'mytable' replace with your table name and 'date_col' with date column.
date() you have used will give current date time , so try to use mktime() to get extact date time you want.
you have to change your query little bit, I have modified query below,
$query = mysql_query("SELECT * FROM mytable WHERE date='$dateOfNewData'");
In mysql Date or datetime coulmn should be within ''.

Categories