我正在研究一個項目,以進一步學習php以及如何使用它與mysql數據庫進行交互。該項目是一個論壇,有問題的頁面顯示一個類別中的所有主題。我想知道我是否正在有效地處理我的電話,如果沒有,我怎樣才能構建我的查詢,使他們更有效率?我知道它的一個小問題,那就是在測試之外不使用網站,但我希望早日得到處理。這些數據庫調用可以優化嗎?
<?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> » <a href='index.php'> Categories </a> » <a href='categories.php?cid=".$cid."'> ".$rcatname['cat_name']."</a> » <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 » ".$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>";
}
?>
謝謝你們!
這可能是http://codereview.stackexchange.com/ – 2012-02-29 23:29:59
一個更好的問題** WARNING **你的代碼是SQL注入攻擊非常敏感。 – 2012-02-29 23:32:10
運行性能分析並檢查索引。而其他人則說,減少往返次數可以幫助提高性能(特別是在延遲情況下),因此可以正確編制索引查詢。就個人而言,只有在查詢被參數化查詢取代之後,我纔會觸及此代碼。 – 2012-02-29 23:58:33