Page 1 of 1
Select a single record in MySQL table, and set as variable..
Posted: Mon Mar 15, 2010 3:59 pm
by overview
Hello.
I'm very new to php since I work with ASP for work all the time, so I am finding a few things slightly strange (but for the most part, PHP is nicer to work with).
Anyway, I have an SQL query which selects a single cell from my table which I need to then set as a variable.
Current code (minus the SQL line):
Code: Select all
$year = $_GET['year'];
if($year == '')
{
$year = 2010;
}
Simple huh?
Now, I need to replace '2010' with whatever the highest year is in the table (if published), so I would use this line of SQL:
Code: Select all
SELECT MAX(year) FROM photos WHERE pub = '1';
I have been trying to make some code that gets the value from the table as above, and sets it as the variable $year but have had no luck. Nothing seems to work.
Any suggestions?
Thanks, Alan.
Re: Select a single record in MySQL table, and set as variable..
Posted: Mon Mar 15, 2010 4:35 pm
by Sephern
A simple query will not suffice. You need to actually assign it to a variable.
Code: Select all
$query = mysql_query("SELECT MAX(year) FROM photos WHERE pub = '1'"); //executes the query
$recordset = mysql_fetch_assoc($query); //fetches the recordset result from the query and places it in an array. See also: mysql_fetch_array and mysql_fetch_row
$year = $recordset['year']; //get the relevant column out of your record array
Remember that the only fields that will actually be in the array are the ones you use in your SELECT statement, but it will still be an array, and you should therefore treat it as such. It also means that if you need to get multiple values from 1 record, selecting * only needs to be done once, and you can reference the array from then on.