2012-12-28 56 views
0

嗨,函數返回用戶名

我的函數有什麼問題?它似乎不工作,但我不知道爲什麼。該函數應該返回用戶名:當我在代碼中使用它

function getusername($username) { 
    $sql = "SELECT username FROM users WHERE id='".$username."' LIMIT 1"; 
    $res = mysql_query($sql) or die(mysql_error()); 
    $row = mysql_fetch_assoc($res); 
    return $row['$username']; 

,它不返回任何東西:

if (mysql_num_rows($res) == 1) { 
    echo "<table width='100%'>"; 
    // Check to see if the person accessing this page is logged in 
    if (isset($_SESSION['username'])) { echo "<tr><td colspan='2'><input type='submit' value='Add Reply' onClick=\"window.location = 'post_reply.php?cid=".$cid."&tid=".$tid."'\" /><hr />"; } else { echo "<tr><td colspan='2'><p>Please log in to add your reply.</p><hr /></td></tr>"; } 
    // Fetch all the topic data from the database 
    while ($row = mysql_fetch_assoc($res)) { 
     // Query the posts table for all posts in the specified topic 
     $sql2 = "SELECT * FROM posts WHERE category_id='".$cid."' AND topic_id='".$tid."'"; 
     // Execute the SELECT query 
     $res2 = mysql_query($sql2) or die(mysql_error()); 
     // Fetch all the post data from the database 
     while ($row2 = mysql_fetch_assoc($res2)) { 
      // Echo out the topic post data from the database 
      echo "<tr><td valign='top' style='border: 1px solid blue;'><div style='min-height: 125px;'>".$row['topic_title']."<br />by ".getusername($row2['post_creator'])." - ".convertdate($row2['post_date'])."<hr />".$row2['post_content']."</div></td><td width='200' valign='top' align='center' style='border: 1px solid blue;'>User Info Here</td></tr><tr><td colspan='2'><hr /></td></tr>"; 
     } 
+1

其值得注意的是,這個代碼是容易受到SQL注入攻擊。您應該確保用戶輸入已經過清理,最好使用準備語句,以便數據與查詢本身分開。 – Spike

+0

它只是練習 – theuserkaps

+2

但你正在學習不好的做法 – lam3r4370

回答

3

你應該改變return $row['$username'];return $row['username'];

+0

它不工作,如果我刪除美元符號 – theuserkaps

+0

所以它不會返回任何東西?如果我刪除美元符號, – lam3r4370

0

你在哪裏打電話mysql_connect和mysql_select_db在你的代碼中?

根據我的經驗,最好儘快調用connect函數,並將返回的資源加載到全局變量中,以便它可用於所有函數。例如:

global $dbHandle; 
$dbHandle = mysql_connect("server string"); 

然後你的函數會是這個樣子:

function getusername($username) { 
global $dbHandle; 
$sql = "SELECT username FROM users WHERE id='".$username."' LIMIT 1"; 
$res = mysql_query($sql, $dbHandle) or die(mysql_error()); 
$row = mysql_fetch_assoc($res); 
return $row['$username']; 
} 
1

使用PDO。

你可以閱讀關於它here

如果我能找到一種方法讓你查找';DROP TABLE users;--那麼我可以給你一個非常糟糕的一天。提示:我可以使用$_GET變量選擇一個類別或主題編號嗎?

您還應該使用JOIN

做一個查詢對數據庫優於10:

SELECT posts.*, users.username FROM posts 
JOIN users ON (users.username = posts.post_creator) 
WHERE category_id=:category_id AND topic_id=:topic_id 

美元符號是一個PHP的事情,而不是一個MySQL的事情。

return $row['$username']; 

應該是:

return $row['username']; 
+0

無法正常工作 – theuserkaps