PDO查询未返回预期结果

时间:2013-06-07 22:55:53

标签: php mysql

我正在为我的游戏制作一个论坛。目前我正在编辑编辑功能。我想弄清楚我如何检查登录帐户是否拥有发布消息的播放器。 您使用播放器发布,而不是帐户。你可以有几个玩家。用户可以分配几个“玩家”。如果他们不拥有发布消息的播放器,我想返回false,但如果他们这样做,则为真。

# table accounts
id | username | password

# table posts
id | posterid (this is the player id) | message

# table players
id | account_id | name

这是我走了多远。但无论如何,这都会失败。有一个ID为666的帖子,发布它的玩家归账号34767所有。所以它应该有效。

function can_we_edit_post($pid) {

global $db;

// Let's see if they have permission to edit
$stmt = $db->prepare("SELECT * FROM players pl a JOIN posts p ON p.id = $pid WHERE pl.account_id = 34767");
$stmt->execute(array(34767));
$row = $stmt->fetch();

// Check if we got any rows
if ($row) {
    return true;
} else {
   return false;
}

}

if (can_we_edit_post(666)) {
   echo "You may edit this post.";
} else {
  echo "You do not own this post.";
}

2 个答案:

答案 0 :(得分:1)

您正在使用错误的PDO。你应该这样做:

$stmt = $db->prepare("SELECT * FROM players pl a JOIN posts p ON p.id = :pid WHERE pl.account_id = :id");
$stmt->execute(array(':pid' => $pid, ':id' => 34767));
return (($stmt->rowCount() > 0)? true : false);

PDO和执行是天才,因为你只需提供你想用值替换的键,它就会逃脱并使你无害。

如果查询的其余部分正确,则此代码应该有效。 rowCount返回查询返回的行数。如果您只是想查看它是否返回任何内容,您可以使用此代替使用fetch

答案 1 :(得分:1)

a之后您有错误pl,因此您的查询可能失败

SELECT * FROM players pl a JOIN posts p ON p.id = $pid WHERE pl.account_id = 34767
                         ^

尝试这样的事情(使用占位符来阻止SQL注入) -

// Let's see if they have permission to edit
$stmt = $db->prepare("SELECT * FROM players pl JOIN posts p ON p.id = ? WHERE pl.account_id = ?");
$stmt->execute(array($pid, 34767));
$row = $stmt->rowCount();

看看这个sqlfiddle - http://sqlfiddle.com/#!2/e282a1/2 - 没有a查询返回结果,a查询失败并显示错误。

修改
它可能会为每位玩家返回true,因为您对pl.account_id -

进行了硬编码
WHERE pl.account_id = 34767

并且您未通过向posterid <添加pl.id来验证post.id是否与特定AND p.posterid = pl.id的{​​{1}}相匹配/ p>

JOIN