Using a GET variable in a MySQL/PHP query - php

I'm working with a mysql date column called 'class_of' that has dates ranging from 2014-08-01 to 2019-08-01, all formatted as a date. These dates coincide to what year an article was written.
I have set up my php execution page to grab the year through a url action.
for example - www.mywebsite.com/mypage.php?action=2016
$classOf = ($_GET["action"]);
I now need to somehow use said variable within a mysql query so my php while loop will only echo dates that have for example 2016 within the date.
This is what I have tried
This works, but I need the year to be a variable
$query = 'SELECT * FROM news_content
WHERE
hot = "false"
AND trash="false"
AND class_of = DATE("2020-08-01")
ORDER BY article_id DESC';
I have tried the below, but with no success
$query = 'SELECT * FROM news_content
WHERE
hot = "false"
AND trash="false"
AND class_of = DATE("<?php echo $classOf ?>-08-01")
ORDER BY article_id DESC';
And
$query = 'SELECT * FROM news_content
WHERE
hot = "false"
AND trash="false"
AND class_of = "<?php echo $classOf ?>" ORDER BY article_id DESC';
And
$query = 'SELECT * FROM news_content
WHERE
hot = "false" AND trash="false"
AND class_of
LIKE "%<?php echo $classOf ?>%" ORDER BY article_id DESC
And
$query = 'SELECT *
FROM news_content
WHERE
hot = "false" AND trash="false"
AND class_of =
"<?php date("echo $classOf-08-01")?>" ORDER BY article_id DESC';
All of the above no success.

Use PHP DateTime class to get the full date and then prepared statements to pass the value to SQL.
$date = (new DateTime ($_GET['action'] . '08-01'))->format('Y-m-d');
$stmt = $mysqli->prepare ('SELECT * FROM news_content WHERE hot = "false" AND trash="false" AND class_of=? ORDER BY article_id DESC');
$stmt->bind_param('s', $date);
$stmt->execute();
$result = $stmt->get_result();
If you want to get all records from a matching year then create 2 PHP dates, dateFrom and dateTo, and then use BETWEEN in MySQL query
$dateFrom = (new DateTime ($_GET['action'] . '01-01'))->format('Y-m-d');
$dateTo = (new DateTime ($_GET['action'] . '12-31'))->format('Y-m-d');
$stmt = $mysqli->prepare ('SELECT * FROM news_content WHERE hot = "false" AND trash="false" AND class_of BETWEEN ? AND ? ORDER BY article_id DESC');
$stmt->bind_param('ss', $dateFrom, $dateTo);
$stmt->execute();
$result = $stmt->get_result();

Related

How to LOOP a SELECT query until it finds a data on database (PHP to MySQL)

I wanted to select a row in the database, but if row is not in the database, it should loop until it finds the
This line
$prev_date = date('M d, Y', strtotime($macrodate .' -1 day')); transforms the currentdate to one down (lets say Jun 15, it will transform to Jun 14). And use that date to check if the date is in the database, it not, it will loop and go to Jun 13. Until it could find the date.
How do I do this? What loop should I use?
$query = "SELECT * FROM users_macros WHERE userid = '$userid' AND `date` = '$macrodate'";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) == 0) {
while(1) {
$prev_date = date('M d, Y', strtotime($macrodate .' -1 day'));
$query2 = "SELECT * FROM users_macros WHERE userid = '$userid' AND `date` = '$prev_date'";
$result2 = mysqli_query($con, $query2);
if (mysqli_num_rows($result2) != 0) {
$row2 = mysqli_fetch_assoc($result2);
$targetcarbs = $row2['carbs'];
$targetproteins = $row2['proteins'];
$targetfats = $row2['fats'];
$con->query("INSERT INTO users_macros VALUES('','$userid','$targetproteins','$targetfats','$targetcarbs','$macrodate')");
break;
}
}
}
Don't use a loop. Just use a query that returns the row with the highest date lower than $macrodate. And you can combine that with the INSERT query.
And add a NOT EXISTS criteria to make it select nothing if the given date is already in the table.
Also, use a prepared statement to prevent SQL injection.
$stmt = mysqli_prepare($con, "
INSERT INTO users_macros
SELECT '', userid, proteins, fats, carbs, ? FROM users_macros
FROM users_macros
WHERE userid = ? AND date < ?
AND NOT EXISTS (
SELECT 1 FROM users_macros
WHERE userid = ? AND date = ?
)
ORDER BY date DESC
LIMIT 1");
mysqli_stmt_bind_param($stmt, "sss", $macrodate, $userid, $macrodate, $userid, $macrodate);
mysqli_stmt_execute($stmt);

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

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

Categories