Jump to content

General PHP/MySql coding question


galvin

Recommended Posts

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
}
}

Link to comment
https://forums.phpfreaks.com/topic/238872-general-phpmysql-coding-question/
Share on other sites

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.