I want to retrieve some data from a table where the age is in a certain range.
EXAMPLE
Persons with age from 20 to 30 years. How can I do it? I tried with the following query, but I was unable to get it.
$age="SELECT *
From rec_patient_reg
WHERE p_age >='$afrom' <= '$to'";
$result1=mysql_query($age)
or die(mysql_error());
while($result = mysql_fetch_array($result1)) {
echo "<b>Patient ID</b> = " .$result["Patient_id"] . " <br>";
echo "<b>NAME</b> = ".$result["p_fname"]."<br><br>----------------<br><br>";
Please help me.
I bet you are not getting any error message since you are using mysql. Take a look at this example below,
SELECT *
FROM tableName
WHERE Age >= 20 <= 25
This is not allowed on any other RDBMS but MySQL allows it. What it does is it implictly allows boolean expression on the rightmost side of the filter, eg
SELECT *
FROM tableName
WHERE (Age >= 20) <= 25
So in this case, the value is now parsed into (let's say Age = 5)
WHERE 0 >= 25
causing you to retrieve unexpected result.
You can use BETWEEN if you want to search for ranges,
SELECT *
From rec_patient_reg
WHERE p_age BETWEEN '$afrom' AND '$to'
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
First thing, do not use mysql_* functions as they are deprecated.
Your query should be:
SELECT *
FROM `rec_patient_reg`
WHERE `p_age` BETWEEN '$afrom' AND '$to'
Maybe like this?
$age = "SELECT * FROM rec_patient_reg WHERE p_age >='$afrom' AND p_age <= '$to'";
Related
Is there a limitation with the CONCAT function so that it cannot handle an IF statement? I have this query, that works if it is not a part of a CONCAT but as soon as I put it inside a CONCAT function it gives this error: #1583 - Incorrect parameters in the call to native function 'CONCAT'
SELECT CONCAT((IF(DAYOFYEAR(`deathdatetr`) and DAYOFYEAR(`birthdatetr`),TO_DAYS(`deathdatetr`) - TO_DAYS(`birthdatetr`),(YEAR(`deathdatetr`) - YEAR(`birthdatetr`)) * 365))/365.25 as totaldays, " years old") from tng_people order by totaldays limit 1;
This query should return the oldest person in the database (age in years). The table I am querying contains among other things, birth- and deathdates in the format "1860-07-30".
Can someone help me figure this out?
Your parentheses are messed up. You have a column alias in the middle of the expression. It is not surprising that MySQL is confused, because you seem to be as well.
It is fine to use if() where any expression is expected. I much prefer CASE (it is standard), but because you started with IF():
SELECT CONCAT(IF(DAYOFYEAR(`deathdatetr`) = DAYOFYEAR(`birthdatetr`),
TO_DAYS(`deathdatetr`) - TO_DAYS(`birthdatetr`),
(YEAR(`deathdatetr`) - YEAR(`birthdatetr`)) * 365)
) /365.25, ' years old') as total_years
from tng_people
order by totaldays
limit 1;
I have no idea what this logic is supposed to be doing. It doesn't seem useful, but that is another matter.
If you want the days between to dates:
select (to_days(deathdatetr) - to_days(birthdatetr)) as total_days
I figured it out, thanks to help from #Gordon. Apparently CONCAT() cannot handle what I THINK is called Aliasing, so once I removed that from the CONCAT() (the "...as total_days"), my query worked fine.
SELECT CONCAT ("A", FLOOR((to_days(`deathdatetr`) - to_days(`birthdatetr`))/365.25) ) from tng_people order by (to_days(`deathdatetr`) - to_days(`birthdatetr`)) DESC limit 1
Thanks for the help!
I am having hard time figuring out how I can select records if my (Between From AND To) is missing From.
Eg. On the form I have date range, and if user enters only TO and leaves FROM blank how can I select ALL records up to that point.
My issue occures here,
SELECT * FROM table WHERE date BETWEEN from AND to;
This is my query and I would like to use this same query and just modify my variables so that I don't have to have multiple SELECTS depending on what data was entered.
Thanks
I would suggest that you arrange your application to have two queries:
SELECT *
FROM table
WHERE date BETWEEN $from AND $to
and:
SELECT *
FROM table
WHERE date <= $to
Then choose the query based on whether or not $from is suppled.
Why? Both queries can take advantage of an index on date. In general, MySQL does a poor job of recognizing index usage with an or condition.
Alternatively, you can use AlexK's suggest and set $from to some ridiculously old date and use the query in the OP.
Try something like:
SELECT *
FROM table
WHERE ($from = '' AND date <= $to) OR
(date BETWEEN $from AND $to);
You can either do this with Giorgos' selection above, or using a union:
SELECT *
FROM table
WHERE date BETWEEN $from AND $to
UNION
SELECT *
FROM table
WHERE date <= $to AND $from IS NULL
Personally I think Giorgos' solution is a bit cleaner, but there are times you'll want a UNION so I'm including for completeness sake.
So basically, in my PHPMYADMIN I'm toying around with SQL injections so that I can eventually become a pen tester
SELECT *
FROM `ip` as ipstr
WHERE 'id' = $USERINPUT_HERE
ORDER BY
ipstr.id ASC
LIMIT 0 , 30
I'm having difficulty because it says that 'ipstr' is no longer defined when I try to inject it into my phpmyadmin.
I know that if it were a subquery, I would be able to do this. But its not a subquery, so how can I make something like the following work?
SELECT *
FROM `ip` as ipstr
WHERE 'id' = $USERINPUT_HERE
UNION ALL SELECT 1,2,3,4,5
ORDER BY
ipstr.id ASC
LIMIT 0 , 30
Somebody I know is saying it is possible to do this kind of injection, but I cannot figure out how to do it without rewriting the whole query and using subqueries. Thanks.
Let's see. If the string contained ''; delete ip; select * from (select 1 as id) ipstr, then the code might do something you don't expect. (To be honest, the entire statement might get rejected because it is multiple statements, but this is an example.)
The solution to SQL injection is to use parameterized queries. This is not a hard concept. And it is a good habit. You should get into that habit.
I'm having trouble with one of my MySQL queries:
SELECT id,Portfolio,Agency,Program,Objective,billion1,value11_12,
Proportion1,billion,value12_13,Percentage,Difference,
Diff_Percent,PIT,TOS,Actual_PIT,Actual_TOS,SUM(billion),SUM(Percentage),
SUM(PIT),SUM(TOS),SUM(Actual_PIT),SUM(Actual_TOS)
FROM budget_table
GROUP BY 'sum(Billion)'
WITH ROLLUP
LIMIT 0,100
The query works but I can't get the limit to work with the rollup. You can see the results of the query at BudgetAus
It is totalling all results rather than the first 100 which is what I am now trying to achieve. I have also tried just using LIMIT 100 but can't get anything to work. I tried using EXPLAIN (for the first time) in MySQL on the database and it said that the query executed although I didn't see any results- but as I've never used it before I wasn't sure what to look for. I'm new to programming and use WAMP rather than a CLI.
I'm also not sure whether to start my limits from 0 or 1?
GROUP BY 'sum(Billion)'
This does not group by each distinct value of the Billion column. This groups by a single value, the constant string literal 'sum(Billion)'. So you'll get one group, because all rows have the same value when you use a constant string literal as your grouping expression.
Take the quotes off when you put an expression in the GROUP BY column.
Then you'll find that this is not a valid expression for grouping anyway.
SUM() operators can't be used in the GROUP BY expression, as SUM() is an aggregate operator, and hence makes no sense inside a GROUP BY
Therefore you should be using id, or some other field, for the GROUP BY.
The second parameter to LIMIT (the offset parameter) starts at 0, not 1.
My son (who is around here somewhere but I don't know his username) decided he wanted to solve this for me today and provided the following solution:
//Get the main result set
$result = mysql_query("SELECT * FROM budget_table ORDER BY Percentage DESC LIMIT 0,100 ");
//Build an array of the ids for the result set
$ids = array();
$rows = mysql_num_rows($result);
//Get id for each row and add to the ids
for($i = 0; $i < $rows; $i++) $ids[] = mysql_result($result, $i, "id");
//Join the ids into a string for use with IN()
$ids_str = implode(",", $ids);
//Get the sums for only the ids of the resultset above
$result2 = mysql_query("SELECT SUM(billion),SUM(Percentage),SUM(PIT),SUM(TOS),SUM(Actual_PIT),SUM(Actual_TOS) FROM budget_table WHERE id IN($ids_str)");
How do I convert a MySQL query with LIMIT to a SQL Server query?
SELECT *
FROM tableEating
WHERE person = '$identity'
LIMIT 1;
LIMIT does not work in T-SQL. Use TOP instead:
SELECT TOP(1) * FROM tableEating WHERE person = '$identity';
As Aaron says, you also need an ORDER BY if you don't want to get an arbitrary row.
LIMIT does not work and TOP(1) may also not work in nested statements.
So the right approach is to use OFFSET... FETCH NEXT:
SELECT * FROM TableName
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
That basically tells TSQL to take one row (NEXT 1 ROWS ONLY) starting from the first one (OFFSET 0).
Take a look at the Microsoft page for 2008, later versions work the same way. If you like to do it dynamic use:
DECLARE #xCount INT = 20
SELECT TOP(#xCount) * FROM ...