...

View Full Version : efficient mySQL selects using PHP



Bobafart
07-12-2007, 05:21 PM
what's the most efficient way to grab a single data value from a table field using PHP?

the best I have is using a while loop -- but something tells me there is a cleaner/more efficient way:



$sql="select countryType from c_countries where userid={$_SESSION[userid]}";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){ $userCountryType = $row[countryType]; }

StupidRalph
07-12-2007, 05:56 PM
Have a look at mysql_result() (http://www.php.net/mysql-result)



$sql="select countryType from c_countries where userid={$_SESSION[userid]}";
$result=mysql_query($sql);
$userCountryType = mysql_result($result,0,0); //the last parameter depends on how the DB table is set up. This will return the first field of the first row.

Fumigator
07-12-2007, 06:41 PM
StupidRalph is spot on... just keep in mind you don't need a loop unless the query results are going to produce more than one row, so using mysql_fetch_array() without the while loop would also be fine.

StupidRalph
07-12-2007, 07:44 PM
StupidRalph is spot on... just keep in mind you don't need a loop unless the query results are going to produce more than one row, so using mysql_fetch_array() without the while loop would also be fine.

I've recently reached my 500 post. I know what level you and the rest of the "Senior Coders" post. I don't want to hurt the ranking system's credibility too much. :p



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum