Prevent repetitive rows - php

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 ''.

Related

Why does this MySQL Update query not work?

Here is my code for updating the date field for all records that have the field WorkoutID = $currentWorkoutID. When I run the query the dates change to 0000-00-00 and not to the current date. How can I fix this? Btw DB::getInstance() executes the query. I think something is wrong with the actual query?
$currentWorkoutID = $_SESSION['GlobalWorkoutID'];
echo $currentWorkoutID;
$date = date("y/m/d");
echo $date;
$sql = "UPDATE workout SET Date = ".$date." WHERE WorkoutID = ".$currentWorkoutID."";
DB::getInstance()->query($sql);
include single quotes ' for date
$sql = "UPDATE workout SET Date = '".$date."' WHERE WorkoutID = ".$currentWorkoutID."";
^ ^
i agrre with the answer
$sql = "UPDATE workout SET Date = '".$date."' WHERE WorkoutID = ".$currentWorkoutID."";
because maybe the type of Date is String ,
hope to help you,thank you
Try this
$sql = "UPDATE workout SET `Date` = '".$date."' WHERE WorkoutID = ".$currentWorkoutID."";
Because date is a reserved keyword

SQL order by date, time [duplicate]

This question already exists:
SQL order by date, time [duplicate]
Closed 9 years ago.
I have table named notify with (seeker, donor, date) columns
the date column of type (datetime) and it stores the following format YYYY-MM-DD HH:MM:SS I'm trying to SELECT 1 record with the latest date from notify table and then compare the date with the current date and calculate the number of days between tow dates..
<?php
session_start();
$email = $_GET['email'];
date_default_timezone_set('Asia/Riyadh');
$time = date("Y-m-d H:i:s");
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']."'AND donor='".$email."' ORDER_BY `date` DESC LIMIT 1";
$st = $conn->prepare($note);
$st->execute();
if($found = $st->fetch(PDO::FETCH_ASSOC)){
$now = $time;
$old_date = strtotime($found['date']);
$dateif = $now - $old_date;
if(floor($dateif/(60*60*24)) >= 7){
echo "the difference between tow dates is 7 days or more";
} else { echo "difference between tow dates is less than 7 days";}
}
?>
the code is not working ! i have only one record in my notify table with this value in date 2013-04-22 09:15:47
First of all, you should use prepared statements like this:
$note = "SELECT *
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
Without the place holders you're still open to SQL injection.
Second, you can't compare a string with an integer in this way:
$now = $time; // string
$old_date = strtotime($found['date']); // integer
$dateif = $now - $old_date; // dunno?
You should compare apples with apples:
$seven_days_ago = strtotime('-7 days');
$old_date = strtotime($found['date']);
if ($old_date > $seven_days_ago) {
echo "difference between tow dates is less than 7 days";
} else {
echo "the difference between tow dates is 7 days or more";
}
Since your date column doesn't exist, there's no point in ordering by it. Also, you're exposed to SQL injection in the case where $_SESSION['email'] is not secured.
So, the correct form would be to use prepared statements, as well as order by the right column. (assuming PDO, you can use mysqli as well):
/** #var PDO $pdo - Assuming a PDO connection. */
$query = "SELECT * FROM `user` WHERE `ID` = :email ORDER BY `time` DESC";
$stmt = $pdo->prepare($query);
$stmt->execute(array($_SESSION['email']));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); //Get all results in an associated array form.
Jack's answer shows you how to use prepared statements correctly. Here is the code to simplify the date calculation using DATEDIFF().
$note = "SELECT *, DATEDIFF(NOW(), `date`) AS date_diff
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER_BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
$row = $st->fetch(PDO::FETCH_ASSOC);
// do something with $row
If you are attching any variables to string then you need to concatinate them using dot and oder by will come after where condition and inside $_SESSION you missed quotes
$query = "SELECT * FROM user WHERE ID='".$_SESSION['email']."' ORDER_BY date, time";
For retrieving latest date from database please try executing following sql query
$query="SELECT * FROM user WHERE ID='".mysql_real_escape_string($_SESSION[email])."' ORDER_BY date,time desc limit 1";
In order to retrieve latest date you need to sort field for date in descending order
$note = "SELECT * FROM notify WHERE seeker=' ".$_SESSION['email']. " ' AND donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
have you try to order by desc? as shown bellow:
$note = "SELECT * FROM notify
WHERE
seeker=' ".$_SESSION['email']. " '
AND
donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
you forgot ` here around date. date is reserved word in mysql,
if you want to use it as column name place ` around it.
EDIT also you have extra space remove it
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']. "'
AND donor='".$email."' ORDER_BY `date` LIMIT 1";

ORDER_BY date LIMIT 1 [duplicate]

This question already exists:
SQL order by date, time [duplicate]
Closed 9 years ago.
I have table named notify with (seeker, donor, date) columns
the date column of type (datetime) and it stores the following format YYYY-MM-DD HH:MM:SS I'm trying to SELECT 1 record with the latest date from notify table and then compare the date with the current date and calculate the number of days between tow dates..
<?php
session_start();
$email = $_GET['email'];
date_default_timezone_set('Asia/Riyadh');
$time = date("Y-m-d H:i:s");
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']."'AND donor='".$email."' ORDER_BY `date` DESC LIMIT 1";
$st = $conn->prepare($note);
$st->execute();
if($found = $st->fetch(PDO::FETCH_ASSOC)){
$now = $time;
$old_date = strtotime($found['date']);
$dateif = $now - $old_date;
if(floor($dateif/(60*60*24)) >= 7){
echo "the difference between tow dates is 7 days or more";
} else { echo "difference between tow dates is less than 7 days";}
}
?>
the code is not working ! i have only one record in my notify table with this value in date 2013-04-22 09:15:47
First of all, you should use prepared statements like this:
$note = "SELECT *
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
Without the place holders you're still open to SQL injection.
Second, you can't compare a string with an integer in this way:
$now = $time; // string
$old_date = strtotime($found['date']); // integer
$dateif = $now - $old_date; // dunno?
You should compare apples with apples:
$seven_days_ago = strtotime('-7 days');
$old_date = strtotime($found['date']);
if ($old_date > $seven_days_ago) {
echo "difference between tow dates is less than 7 days";
} else {
echo "the difference between tow dates is 7 days or more";
}
Since your date column doesn't exist, there's no point in ordering by it. Also, you're exposed to SQL injection in the case where $_SESSION['email'] is not secured.
So, the correct form would be to use prepared statements, as well as order by the right column. (assuming PDO, you can use mysqli as well):
/** #var PDO $pdo - Assuming a PDO connection. */
$query = "SELECT * FROM `user` WHERE `ID` = :email ORDER BY `time` DESC";
$stmt = $pdo->prepare($query);
$stmt->execute(array($_SESSION['email']));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); //Get all results in an associated array form.
Jack's answer shows you how to use prepared statements correctly. Here is the code to simplify the date calculation using DATEDIFF().
$note = "SELECT *, DATEDIFF(NOW(), `date`) AS date_diff
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER_BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
$row = $st->fetch(PDO::FETCH_ASSOC);
// do something with $row
If you are attching any variables to string then you need to concatinate them using dot and oder by will come after where condition and inside $_SESSION you missed quotes
$query = "SELECT * FROM user WHERE ID='".$_SESSION['email']."' ORDER_BY date, time";
For retrieving latest date from database please try executing following sql query
$query="SELECT * FROM user WHERE ID='".mysql_real_escape_string($_SESSION[email])."' ORDER_BY date,time desc limit 1";
In order to retrieve latest date you need to sort field for date in descending order
$note = "SELECT * FROM notify WHERE seeker=' ".$_SESSION['email']. " ' AND donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
have you try to order by desc? as shown bellow:
$note = "SELECT * FROM notify
WHERE
seeker=' ".$_SESSION['email']. " '
AND
donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
you forgot ` here around date. date is reserved word in mysql,
if you want to use it as column name place ` around it.
EDIT also you have extra space remove it
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']. "'
AND donor='".$email."' ORDER_BY `date` LIMIT 1";

How can I add array values to a MySQL query?

I'm using the following code to sort MySQL queries into time/date:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row = mysql_fetch_array($result))
{
print($row['user']);
}
instead of having the PHP run through and show all the values in the table can I have it show the values from an array?
So, you want to find specific users in the SQL query to return? Build your query programmatically:
$users = array('User1','John','Pete Allport','etc');
$sql = "SELECT * FROM `users_newest_post` WHERE ";
$i = 1;
foreach($users as $user)
{
$sql .= "`username` = '$user'";
if($i != count($users))
{
$sql .= " OR ";
}
$i++;
}
$sql .= " ORDER BY `users_date_post` DESC";
$result = mysql_query($sql);
Which would get you a query like:
SELECT * FROM `users_newest_post`
WHERE `username` = 'User1'
OR `username` = 'John'
OR `username` = 'Pete Allport'
OR `username` = 'etc'
ORDER BY `users_date_post`
DESC
So, you want to find all posts for a certain date or between two dates, kinda hard to do it without knowing the table structure, but you'd do it with something like this:
//Here's how to find all posts for a single date for all users
$date = date('Y-m-d',$timestamp);
//You'd pull the timestamp/date in from a form on another page or where ever
//Like a calendar with links on the days which have posts and pass the day
//selected through $_GET like page.php?date=1302115769
//timestamps are in UNIX timestamp format, such as you'd get from time() or strtotime()
//Note that, without a timestamp parameter passed to date() it uses the current time() instead
$sql = "SELECT * FROM `posts` WHERE `users_date_post` = '$date'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
echo $row['post_name'] . $row['users_date_post']; //output something from the posts
}
//Here's how to find all posts for a range of dates
$startdate = date('Y-m-d',$starttimestamp);
$enddate = date('Y-m-d',$endtimestamp);
//Yet again, date ranges need to be pulled in from somewhere, like $_GET or a POSTed form.
//Can also just pull in a formatted date rather than a timestamp and use it straight up instead, rather than going through date()
$sql = "SELECT * FROM `posts` WHERE `users_date_post` BETWEEN '$startdate' AND '$enddate'";
//could also do:
//"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$endate'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
//output data
}
To find posts for a specific user you would modify the statement to be something like:
$userid = 5; //Pulled in from form or $_GET or whatever
"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$enddate' AND `userid` = $userid"
To dump the result into an array do the following:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row=mysql_fetch_assoc($result))
{
$newarray[]=$row
}
What you probably want to do is this:
$users = array("Pete", "Jon", "Steffi");
$users = array_map("mysql_real_escape_string", $users);
$users = implode(",", $users);
..("SELECT * FROM users_newest_post WHERE FIND_IN_SET(user, '$users')");
The FIND_IN_SET function is a but inefficient for this purpose. But you could transition to an IN clause with a bit more typing if there's a real need.
$sql = 'SELECT * FROM `users_newest_post` WHERE username IN (' . implode(',', $users) . ')';

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

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'];

Categories