The following articles were found with tag phpalized:
Bad Practice: DB Queries inside loops
Sat Sep 29, 2007 at 03.37
This is something I see day in and day out, and unfortunately is a deep gash into the good reputation of otherwise awesome PHP coders. If you ever find yourself putting a database query inside a loop, stop and study the code for a long moment. Chances are this is unnecessary.
Generally speaking the only acceptable time for a query to be inside a loop is when it is contained in a script that will only be used once and that is meant to do some sort of data transfer/transformation (which can probably be better accomplished using a pure SQL solution, but that is a battle for another day.)
So let's examine one of the more common occurrences of this problem:
, SUM(points) total_points
FROM user_points
GROUP BY user_id
ORDER BY total_points DESC";
$query_1 = mysql_query($sql_1) or die(mysql_error() . "<br />" . $sql_1);
while($row_1 = mysql_fetch_assoc( $query_1 )) {
$sql_2 = "SELECT first_name
, last_name
FROM users
WHERE user_id = " . $row_1['user_id'];
$query_2 = mysql_query( $sql_2 ) or die( mysql_error() . "<br />" . $sql_2);
//more code follows
}
If you recognize this code and are thinking, "Hey man, what's wrong with that? That's how I always do it!" then I am extremely happy that you are reading this post.
The problem is that we really don't know how many users there are - and even if we did this is still a bad solution - in the user_points table and thus we are repeating the query to get the user's name an unknown number of times (N times.) This is a resource hog of a script to do something that is simple to accomplish using the proper query.
In this case, had we known about and employed an INNER JOIN, we will eliminate the subsequent calls to the database and retrieved all the information we need in one trip. This terminates the script's connection to the database quicker and allows another connection to be established by a different script. This is a good thing, trust me. If you have ever had to figure out what is causing your server to crawl you will know that I speak the truth.
So how do we solve the problem? As stated above we take that query and get the information using an INNER JOIN. Here is our new query
, u.first_name
, u.last_name
, SUM( up.points ) total_points
FROM user_points up
INNER JOIN users u
ON up.user_id = u.user_id
GROUP BY user_id
ORDER BY total_points
If any of that looks foreign to you, it's time you brushed up on your SQL. I suggest reading a few tutorials on JOINs.
- Tagged:
- technicalarticles
- phpalized
- database
- mysql
- php
Debugging MySQL Queries in PHP
Fri Sep 28, 2007 at 23.21
Over at what is becoming my second home a frequently asked question ultimately results in the original poster needed some guidance in debugging interaction between their PHP scripts and their database, namely MySQL. I hope to uncover some best practices for making it easier to figure out what is going on with your script.
This first snippet is a commonly occurring one and will be known as "the hard way" in terms of finding the cause of your incorrect results quickly.
while($row = @mysql_fetch_assoc($result)) {
echo $row['user_id'] . " " . $row['username'];
}
This is the hard way because we have suppressed any errors using the @ operator and assumed that there will always be results. If something goes wrong, we might be surprised, or even worse just assume that there aren't any results that match our query. The query from above is rather simple and will probably not produce an error, but once you get into more involved queries you might have a mistake or two. Which brings me to my first point: you should create your queries outside of PHP (e.g. on the command line or in a product such as MySQL Query Browser or PhpMyAdmin) and ensure that they are working before adding them to the equation in your script.
Once you have your query working correctly directly against the database add it to your script with a few additions to the above code. First we will utilize the native function mysql_error to return the error from the MySQL engine and use it to show us exactly what went wrong. This coupled with the display of the query that was actually sent to the engine will prove extremely helpful in the future. This is how a query snippet might look with some more debugging features
$result = mysql_query($sql) or die("MySQL error: " . mysql_error() . " generated by " . $sql);
In the event of a failed query, we can now see the error generated by the db engine and the actual query that caused the error. This however is not something you should find in a production environment. The reason is outside the scope of this post, but involves security by not hinting at database structure.
When handling the utilization of result sets the result set should first be verified. We did not do this in our first example we just assumed that there were rows and that the query was successful. That can also be handled better using the following snippet
echo "Database query returned an error.";
}
elseif( mysql_num_rows( $result ) == 0 ) {
echo "There were no results returned.";
}
else {
while($row = mysql_fetch_assoc( $result) ) {
echo $row['user_id'] . " " . $row['user_name'];
}
}
Naturally you will probably want to handle the cases a little differently (i.e. not just echo out those simple statements) but you get the general idea.
- Tagged:
- technicalarticles
- phpalized
- database
- mysql
- php