I have 2 tables as follow :
table1 has these fields:
year,day,month,name
table2 has these fields:
years,gift
I want to return the rows where year = years. the two queries NEED to be run separately that is a condition.
I CANNOT join them into 1 query (I know how to do that but that’s not how this should be done). Any suggestions? I thought of using a foreach loop but failed to implement, any ideas?
$sql1 = " SELECT * FROM table1 ORDER BY id ASC";
$result1 = mysql_query($sql1);
$rows = mysql_fetch_array($result1);
while($rows = mysql_fetch_array($result1))
{
$year[] = $rows['year'];
}
$sqlx = "SELECT * FROM table2";
$result = mysql_query($sqlx);
while($row = mysql_fetch_array($result))
{
$years[] = $rows['years'];
}
This is a strange requirement, since it should be done with a join. It is vastly less efficient to do this with multiple queries in a loop than a single query with a
JOIN.In any case if you must do it this way, you have retrieved the years into an array correctly from your first query — use that array to populate the query for each loop iteration of your second query:
Update:
This can be accomplished with a creative
JOINusing date functions. Assumingtable2.yearsis aDATEorDATETIME, useYEAR()to return only the year portion from it, and compare it toYEAR(CURDATE())for the current year. Join that against the number of years intable1.year.