PHP MySQL Select * From Where Date < today - php

So I am building a function that prints out a league schedule. I've run into a little snag when trying to pull the last 5 matches. Here is my code:
$league ID, $direction and $limit are set by the functions parameters.
$matches = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'leagueDesigner_season_matches WHERE leagueID = ' . $leagueID . ' and date < CURRENT_DATE() ORDER BY date ' . $direction . ' LIMIT 0, ' . $limit);
Appologies, I forgot to finish the post. The code is returning all dates and not just the dates before today.

The most likely explanation for the behavior you observe is that the column named date is defined as a datatype other than DATE, DATETIME, or TIMESTAMP. (Likely, you've defined it as an integer or varchar), and MySQL is not doing a "date" comparison, it's comparing strings or integers.
But absent the definition of the date column, that's just conjecture.
If the "snag" you've hit is an error being returned from MySQL, my recommendation for debugging issues with SQL statements is to you build your SQL text into a string variable, as a separate step, and then echo (or printf or vardump) the contents of the variable containing the SQL text, before you try to execute it.
$sql = "SELECT foo FROM bar WHERE fee = " . $val . " ORDER BY foo DESC LIMIT 1 ";
echo $sql;
And verify that the string echoed out is the SQL text you intend to send to the database; taking that string and attempting to execute it through another MySQL client is an effective way of verifying the statement executes and returns the resultset you expect.
If you use any reserved words as column names, you may need to qualify those column names with a tablename, rowsource alias, etc., or enclose it in backticks. (EDIT: DATE is not a reserved word in MySQL 5.5)
... FROM mytable t WHERE t.date = ...
or
... FROM mytable t WHERE `date` = ...
Also note that including "unsafe" variables in SQL text can lead to SQL injection vulnerabilities.
For example,
$val = '1 OR 1=1';
$sql = "SELECT * FROM mytable WHERE id = ' . $val ;

Related

PDO changes query

I want to have result of my query as it was before I replaced db connection using PDO. How can I get the query as i t was before I implemented PDO?
This is my query:
$query =
"SELECT
`id_affirmation`,
`affirmation`,
`author`,
`user_rate`,
am.date,
am.time,
hua.date,
hua.time
FROM `affirmation_male` am
JOIN `history_user_affirmation` hua ON am.id_affirmation = ua.affirmation_id
WHERE hua.user_id = '" . $id_user . "'
ORDER BY
STR_TO_DATE(hua.date, '%d-%m-%Y') DESC,
hua.time DESC";
For some reason the result of query when I use PDO is i got date from affirmation_male. Do you know why?
Your query returns two columns that have the same name, hence PDO gets lost when it fetches the results; since each records is represented as an associative array, duplicate keys generate ambiguity (only one key will be retained).
You would need to alias those columns to remove ambiguity:
$query =
"SELECT
`id_affirmation`,
`affirmation`,
`author`,
`user_rate`,
am.date am_date,
am.time am_time,
hua.date AS hua_date,
hua.time AS hua_time
FROM `affirmation_male` am
JOIN `history_user_affirmation` hua ON am.id_affirmation = hua.affirmation_id
WHERE hua.user_id = '" . $id_user . "'
ORDER BY
STR_TO_DATE(hua.date, '%d-%m-%Y') DESC,
hua.time DESC";
Notes:
it would also be a good idea to prefix the first columns in the query with the alias of the table they belong to, as this makes the query more readable (and will avoid conflicts if ever these columns names were available in more than one table coming into play in the query)
you could remove backticks to make the query more readable, as the column and table names that you are quoting do not seem to contain any special characters

How to use prepare() with dynamic column names?

I have a function that takes an sql table column name string as a parameter, returns 1 string result:
function myFunction($column_name) {
return $wpdb->get_var($wpdb->prepare("SELECT %s FROM myTable WHERE user_id=%s", $column_name, $current_user->user_login));
}
However, this code does NOT work, since with the nature of prepare, I can't use a variable for column names (and table names).
This works, but I think it poses a security issue:
return $wpdb->get_var('SELECT ' . $column_name . ' FROM myTable WHERE user_id=' . $current_user->user_login);
What do I need to do in order to to use dynamic column names in my prepare statement?
You could use a list of "approved" values instead, that way you're not really using user data inside a query. Something like this:
$Approved = array ('firstname', 'lastname', 'birthdate') ;
$Location = array_search($ColumnName, $Approved) // Returns approved column location as int
if($Location !== FALSE) {
// Use the value from Approved using $Location as a key
$Query = $wpdb->Prepare('SELECT ' . $Approved[$Location] . ' FROM myTable WHERE user_id=:userid');
$Query->Execute(array(
:userid => $current_user->user_login
));
return $Query;
} else {
return false;
}
Maybe it might be easier to just get all (SELECT * or SELECT a,b,c,d) of the user data and save it to session to use later?
It only took 8 years! But it looks like a fix is finally coming to WordPress in milestone 6.2, where all you'll have to do is use %i instead of %s as a placeholder inside $wpdb-prepare() statements for table and column names. Here's a dev-note about it with examples.
Will update this answer once milestone 6.2 is live (looks like it's currently slated for Mar 28).

Select rows between two dates where dates are variables

I have an SELECT statement in php and I need to select all rows of the table where the "date" column is in between a start date and end date that will be defined by variables.
I have this working perfectly fine when I define the dates directly in the SELECT statement as shown below:
date BETWEEN "2015-02-03" AND "2015-02-05"
However, when I try to do the same thing but with variables, it doesn't seem to work:
date BETWEEN "$startdate" AND "$enddate"
Where
$startdate = "2015-02-03";
$enddate = "2015-02-05";
Hope all this makes sense, Cheers in advance.
Full code snippet is here as requested:
$startdate = "2015-02-03";
$enddate = "2015-02-05";
$sql = 'SELECT record_number, date, manmod, description, cal, serial, datein, dateout, retdate, refex, refexdate, sellersname, sellersaddress, buyersname, buyersaddress, rfddealer, del, warranty, months FROM record WHERE del="Live" AND date BETWEEN "$startdate" AND "$enddate" ORDER BY record_number DESC';
From the PHP website:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
In other words, since your query is in single quotes, the $startdate and $enddate variables are not interpreted as variables. The SQL query that is send to the database will literally contain $startdate and $enddate, and will therefore look something like this:
'SELECT column1, column2 FROM table WHERE date BETWEEN "$startdate" AND "$enddate" ORDER BY record_number DESC';
(I've simplified the query a bit for readability purposes)
Obviously, the database does not know how to interpret PHP variables, it will look for records with a date between those two strings, finds nothing and therefore returns 0 records.
In order to paste the contents of the variables in your SQL query, you will have to do one of two things:
Option 1: replace the single quotes with double quotes
If you choose this option, make sure that you either escape the existing double quotes, or change them into single quotes:
$sql = "SELECT column1, column2 FROM table WHERE date BETWEEN '$startdate' AND '$enddate' ORDER BY record_number DESC";
Option 2: concatenate the strings manually
You can also build op the query manually from multiple parts, and glue them together using PHP's concatenation operator, the dot (.).
$sql = 'SELECT column1, column2 FROM table WHERE date BETWEEN "' . $startdate . '" AND "' . $enddate;
You should convert it to a greater than and less than equation:
date > '$startdate' AND date < '$enddate'
The issue isn't with your SQL, but with your PHP.
You need to read up on how string concatenation works and how PHP treats strings that use ' and " differently when wrapped around strings.
$sql = 'SELECT * FROM record WHERE date BETWEEN "$startdate" AND "$enddate"';
Should be changed to one of the following:
$sql = 'SELECT * FROM record WHERE date BETWEEN "' . $startdate . '" AND "' . $enddate . '"';
OR:
$sql = "SELECT * FROM record WHERE date BETWEEN '$startdate' AND '$enddate'";
I've simplified the SQL to highlight the real issue at hand.

php mysql comparing dates for equality

I am using php to access fields from 2 tables.
This part works just fine
$sql=mysql_query('SELECT * FROM user_weeks WHERE user_id = '.$_SESSION["user_id"].' ORDER BY date DESC') or die(mysql_error());
I get the date just fine by doing this
$infodate=$info["date"];
echo $infodate;
However I'm trying to take that date and compare it to one in a different table as such
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE date = '.$infodate.' ') or die(mysql_error());
however, that gives me no results. I'm a noob so sorry if this code is so "2000 and late"
Assuming both date fields are of type date, you need to wrap the name date in backticks, since date is a reserved word and you need to wrap your date in quotes.
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE `date` = "'.$infodate. '"') or die(mysql_error());
Also, mysql_* functions are deprecated. You need to look into using PDO or mysqli to query your database.
date is reserved word use to wrap inside the backtick `date
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE `date` = "'.$infodate.'" ') or die(mysql_error());
Presumably you're using a standard yyyy-mm-dd type date string in your query, which means you're lacking quotes around the date value:
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE date = '.$infodate.' ')
^--here ^-- here
Your query will look like
... WHERE date = 2013-12-18
and be evaluated as a simple mathematical subtraction:
... WHERE date = 1983
You need quotes:
.... date = "' . $infodate . '"');
^-- ^--

Syntax error in MySql using subqueries

Below is MySql query:
$queryfilter = "SELECT * FROM tablename where sector = " .$_SESSION['idfilterdrop']. " AND
region IN (SELECT region from
tablename where sector = " . $_SESSION['sector'] ." OR region = " .
$_SESSION['r1'] ." OR theme = " . $_SESSION['theme'] .")";
Help me to find the syntax error. I am sure there is a problem of double quotes in the above query. When I run this query on MySql prompt it runs fine but when I replace the constant value with variables this query doesn't work.
Unfortunately, we don't know if your $_SESSION array contains integers or strings. if the elements sector, r1 or theme are strings, you need to quote them in your SQL, like this: WHERE sector = '". $_SESSION['sector'] . "' OR.
Also, your table being named database does not help. If I recall correctly, DATABASE is a reserved word, so you'll need to put backtics around that table name:
... FROM `database` ...

Categories