galvin Posted June 9, 2011 Share Posted June 9, 2011 I have code like below that loops thru a certain amount of times and grabs data from a database each time. It works fine, but I am curious if it is bad practice to repeatedly grab info from mysql like that. In other words, would it be better/more efficient to query the database ONCE and then create an array and the loop thru the array? Or does querying the database multiple times not really affect anything negatively? for ($i=1; $i<=$number;$i++) { $sql = "SELECT * FROM table WHERE quizid = $quizid AND id=$i"; $getinfo = mysql_query($sql, $connection); if (!$getinfo) { die("Database query failed: " . mysql_error()); } else { //do stuff } } Quote Link to comment Share on other sites More sharing options...
WebStyles Posted June 9, 2011 Share Posted June 9, 2011 It kind of depends on how large your database is, how much stuff you'll be doing, how long the database connection will be open, and how many simultaneous connections vs how much traffic you have. Quote Link to comment Share on other sites More sharing options...
QuickOldCar Posted June 9, 2011 Share Posted June 9, 2011 Gotta agree with webstyles. You can lessen the "load" by caching, creating indexes in mysql on any where,or,and statements, is also query caching. Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted June 9, 2011 Share Posted June 9, 2011 You should (almost) never put a query inside a loop to get a SET of related/similar records from your database. You form and execute ONE query that gets all the records you want in the order that you want them and then SIMPLY iterate over the set of data that the query returns. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.