In MySQL I am trying to select only the distinct years from over a thousand rows using a textual field called 'edate' that is formatted "1-Jan-2010":
SELECT DISTINCT DATE_FORMAT(STR_TO_DATE(edate, '%e-%b-%Y'), %Y) FROM addnews WHERE status = 1 AND archives = 1 AND delete1 = 0
Devoluciones de MySQL
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\WAMP\www\baycrossings\web\archives.php on line 28"
In MS SQL this works as follows:
select distinct(year(edate)) from addnews where status = 1 and archives = 1 and delete1 = 0
Does MySQL not allow substring selection? I am trying to avoid selecting hundreds of times more data than I need per query.
preguntado el 28 de agosto de 11 a las 03:08
Did you forget to quote the
%Y segundo argumento para
Try changing your query call to look like this:
$result = mysql_query($your_query) or trigger_error(mysql_error());
That way you can see the actual error that MySQL is returning, as opposed to just an error about mysql_query() returning FALSE (which is what the error you pasted is saying).
Beyond that, you should not be storing dates as strings in the database. The native date field types should be used, as they allow date 'math' to be peformed without having to do some very expensive string-to-date conversion.
Since you're just trying to extract a year from a string date, assuming the date format is constant, try using:
SELECT ..., RIGHT(edate, 4)
which will be a far faster operation than a string-to-date-to-string round trip operation.
Is there a reason you're not just using the YEAR function in MySQL as well?
Anyway, the problem with your current query is that you need to put the
%Y in single quotes, like this:
SELECT DISTINCT DATE_FORMAT(STR_TO_DATE(edate, '%e-%b-%Y'), '%Y') FROM addnews WHERE status=1 AND archives=1 AND delete1=0
If you get that "boolean" error with a MySQL operation, it generally means your query failed, and the PHP query function has returned a boolean false. Your code should look like this:
$sql = "..."; $result = mysql_query($sql) or die(mysql_error());
If your query is invalid (syntax error, fails constraints, etc...), this construct will kill your script and output the exact reason for the error. Without the
or die(), your could would take the boolean false that msyql_query() returns, and attempt to do another operation (fetch?), which now also fails, because you can't fetch a row from a "FALSE".