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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.