seniramsu Posted May 6, 2010 Share Posted May 6, 2010 I'm pretty new to php and I'm trying to figure out a better way to query a database for, say, a row of data, and then assign the values returned to variables. Here's what I've tried so far...it seems like there's gotta be a more efficient way out there... Here's a Barney-style example... //example $query = "SELECT * FROM `database`.`table` WHERE `id` = 1"; $result = mysql_query($query, $connection); while (isset($result)) { $row = mysql_fetch_assoc($result); $id = $row['id']; $name = $row['name']; $stuff = $row['stuff']; break; // I have to put a break, otherwise the page will never load } the thing that's screwing me up is having to use that break...it doesn't allow me to access the values of those variables for any other code throughout my page. Any ideas would be greatly appreciated. Cheers! Link to comment https://forums.phpfreaks.com/topic/200855-assigning-variables-to-mysql_fetch_assoc-returned-values/ Share on other sites More sharing options...
trq Posted May 6, 2010 Share Posted May 6, 2010 $result will always be set so your loop will never end. if your only looking for one result, you don't need a loop at all. $query = "SELECT id, name, stuff FROM `database`.`table` WHERE `id` = 1 LIMIT 1"; if ($result = mysql_query($query, $connection)) { if (mysql_num_rows($result)) { $row = mysql_fetch_assoc($result); $id = $row['id']; $name = $row['name']; $stuff = $row['stuff']; } } Link to comment https://forums.phpfreaks.com/topic/200855-assigning-variables-to-mysql_fetch_assoc-returned-values/#findComment-1053919 Share on other sites More sharing options...
seniramsu Posted May 6, 2010 Author Share Posted May 6, 2010 Thanks for your help. Let's say I wanted to query an entire table, would a foreach loop be more efficient? e.g. //example $query = "SELECT * FROM `database`.`table` WHERE `id` > 1"; $result = mysql_query($query, $connection); $row = mysql_fetch_assoc($result); foreach ($row as $key => $value) { $id = $row['id']; $name = $row['name']; $stuff = $row['stuff']; } ? Link to comment https://forums.phpfreaks.com/topic/200855-assigning-variables-to-mysql_fetch_assoc-returned-values/#findComment-1053925 Share on other sites More sharing options...
trq Posted May 6, 2010 Share Posted May 6, 2010 If you want all results you would use a while, but you'll need to store your results within an array. $query = "SELECT * FROM `database`.`table` WHERE `id` > 1"; if ($result = mysql_query($query, $connection)) { if (mysql_num_rows($result)) { $results = array(); while ($row = mysql_fetch_assoc($result); $results[] = $row; } } } Note the if statements as well. you should always check your queries succeed and return results. Link to comment https://forums.phpfreaks.com/topic/200855-assigning-variables-to-mysql_fetch_assoc-returned-values/#findComment-1053927 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.