这些数据库调用可以优化吗?

I'm working on a project to further learn php and how it can be used to interface with a mysql database. The project is a forum, with the page in question displaying all the topics in a category. I'd like to know if I am handling my calls efficiently, and if not, how can I structure my queries so they are more efficient? I know its a small point with a website that isn't used outside of testing, but I'd like to get a handle on this early.

<?php
$cid = $_GET['cid'];
$tid = $_GET['tid'];

// starting breadcrumb stuff
$catname = mysql_query("SELECT cat_name FROM categories WHERE id = '".$cid."'");
$rcatname = mysql_fetch_array( $catname );
$topicname = mysql_query("SELECT topic_title FROM topics WHERE id = '".$tid."'");
$rtopicname = mysql_fetch_array( $topicname );
echo "<p style='padding-left:15px;'><a href='/'> Home </a> &raquo; <a href='index.php'> Categories </a> &raquo; <a href='categories.php?cid=".$cid."'> ".$rcatname['cat_name']."</a> &raquo; <a href='#'> ".$rtopicname['topic_title']. "</a></p>";
//end breadcrumb

$sql = "SELECT * FROM topics WHERE cat_id='".$cid."' AND id='".$tid."' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) == 1) {
    echo "<input type='submit' value='Reply' onClick=\"window.location = 'reply.php?cid=".$cid."&tid=".$tid."'\" />";
    echo "<table>";
    if ($_SESSION['user_id']) { echo "<thead><tr><th>Author</th><th>Topic &raquo; ".$rtopicname['topic_title']."</th></thead><hr />"; 
    } else { 
        echo "<tr><td colspan='2'><p>Please log in to add your reply.</p><hr /></td></tr>"; 
    }
    echo "<tbody>";
    while ($row = mysql_fetch_assoc($res)) {
        $sql2 = "SELECT * FROM posts WHERE cat_id='".$cid."' AND topic_id='".$tid."'";
        $res2 = mysql_query($sql2) or die(mysql_error());
        while ($row2 = mysql_fetch_assoc($res2)) {
            echo "<tr><td width='200' valign='top'>by ".$row2['post_creator']." <hr /> Posted on:<br />".$row2['post_date']."<hr /></td><td valign='top'>".$row2['post_content']."</td></tr>";
        }
        $old_views = $row['topic_views'];
        $new_views = $old_views + 1;
        $sql3 = "UPDATE topics SET topic_views='".$new_views."' WHERE cat_id='".$cid."' AND id='".$tid."' LIMIT 1";
        $res3 = mysql_query($sql3) or die(mysql_error());
        echo "</tbody></table>";
    }
} else {
    echo "<p>This topic does not exist.</p>";
  }
?>

Thanks guys!

Here are some of extra things I would do when I write a code like above:

  1. Never use * in SELECT statement when you know the columns you are going to use.
  2. Always use or die(mysql_error()) when executing the query.
  3. Unset the result sets once the result sets has served its purpose.
  4. Use mysql_real_escape_string() to escape the injections when using some substitutions in your queries.

Looks like a classic (n+1) query mistake that could die a latent death. You get a key using one round trip, then you loop over the results to get n values based on it. If the first result set is large you'll have a lot of network round trips.

You could bring it all back in one go with a JOIN and save yourself a lot of network latency.

The statements themselves are fairly simple so there's not much you can do to optimize them further that I know of. However, if you create some business objects and cache the data into them on a single call and then access data from the business objects then it could be faster.

In other words, 1 SQL call for 1,000 rows is going to be much faster than 1,000 calls for a single row.