您好,
我的功能出了什么问题?它似乎不起作用,但我不知道为什么。该函数应该返回一个用户名:
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>";
}
答案 0 :(得分:3)
您应该将return $row['$username'];
更改为return $row['username'];
答案 1 :(得分:1)
您可以阅读here。
如果我能找到让你抬头';DROP TABLE users;--
的方法,那么我可以给你一个非常糟糕的一天。提示:我可以使用$_GET
vars选择类别或主题编号吗?
对数据库执行一次查询优于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
return $row['$username'];
应该是:
return $row['username'];
答案 2 :(得分: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'];
}