我有一个类似于Facebook的简单留言板页面。用户发布消息,用户可以对此消息发表评论。每条消息都张贴在页面上,并且在每条消息下方都有一个地方可以对该消息提交评论。在我的数据库中,有用于用户,消息和注释的表。
我的问题是:我如何知道我要评论的特定消息,以便将它与相应的message_id正确传递到MySQL数据库?
$comm = "INSERT INTO comments(user_id, message_id, comment, created_at, updated_at)
SELECT '{$_SESSION['id']}', '{$_SESSION['messages.id']}', '{$_SESSION['comment']}', NOW(), NOW()
FROM messages";
编辑:
$query = "SELECT users.first_name AS first_name, users.last_name AS last_name, messages.id AS mess_id,
messages.message AS message, DATE_FORMAT(messages.created_at, '%M %e %Y') AS time
FROM users
LEFT JOIN messages
ON users.id = messages.user_id
ORDER BY time DESC";
$results = fetch($query);
foreach ($results as $row) {
$_SESSION['messages.id'] = $row['mess_id'];
echo
"<div class='post'>".
$row['first_name']. " ". $row['last_name']. " - ". $row['time']. "<br>".
"<p class='mess_content'>". $row['message']. "</p>
</div><br>
<div class='posted_comm'>";
$query = "SELECT users.first_name AS first_name, users.last_name AS last_name,
comments.message_id, DATE_FORMAT(comments.created_at, '%M %e %Y') AS time, comments.comment AS comment
FROM users
LEFT JOIN comments
ON users.id = comments.user_id
WHERE comments.message_id = '{$_SESSION['messages.id']}'
ORDER BY time ASC";
$results1 = fetch($query);
foreach ($results1 as $value) {
echo
"<div class='comments'>".
$value['first_name']. " ". $value['last_name']. " - ". $value['time']. "<br>".
"<p class='comm_content'>". $value['comment']. "</p>
</div><br>";
}
echo "<div class='write_comm'>
<form method='post' action='mess_comm.php'>
<input type='hidden' name='action' value='post_comm'>
Post a comment:<input type='text' name='comm' class='comm'>
<input type='submit' value='Post a comment' class='comm_sub'>
</form>
</div>";
最佳答案
扩展表单,使其包含消息ID作为隐藏字段:
echo "<div class='write_comm'>
<form method='post' action='mess_comm.php'>
<input type='hidden' name='action' value='post_comm'>
<input type='hidden' name='message_id' value='{$row['mess_id']}'>
Post a comment:<input type='text' name='comm' class='comm'>
<input type='submit' value='Post a comment' class='comm_sub'>
</form>
</div>";
然后在查询中使用ID:
$comm = "INSERT INTO comments(user_id, message_id, comment, created_at, updated_at)
VALUES ('{$_SESSION['id']}', '{$_POST['message_id']}', '{$_POST['comm']}', NOW(), NOW())";
注意:我已更正您的INSERT查询中的错误。您应该查看准备好的语句,现在您的代码已可以进行SQL注入。