我建议在用户注册时,为他们分配一个唯一的 ID(或让数据库自动递增)并将其保存在数据库中。然后,每当他们登录时,您都可以从数据库中提取该 user_id 并将其存储在会话变量中。创建呼喊时,您将创建呼喊的人的用户 ID 与呼喊本身一起存储在数据库的呼喊表中。当用户尝试删除喊叫时,您首先检查以确保该喊叫属于他们,然后才允许他们删除它。
一个例子:
<?php
//when user logs in
$email = 'example@example.com';
$password = 'default';
$sql = "SELECT id FROM user_table WHERE email = '$email' AND password = '$password'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$_SESSION['user_id'] = $row['id'] //'id' is the user's id; assign it to the session variable
//user creates the shout
$user_id = $_SESSION['user_id']; //get the user_id from the logged-in user
$shout = $_POST['shout'];
$sql = "INSERT INTO shout_table (user_id, shout) VALUES ('$user_id','$shout')"; //store user id alongside the shout for future queries
mysql_query($sql);
//user about to delete the shout
$id = $_GET['id'];
$user_id = $_SESSION['user_id'];
//the sql to check in the shout_table to see if the shout they are deleting belongs to them
$sql = "SELECT * FROM shout_table WHERE user_id = '$user_id' AND id = '$id'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if ($row)
{
//everything is alright; this user can delete the shout, so prepare the DELETE query to do so
}
else
{
//the user is not allowed to delete the shout because it's not theirs; tell them so with an echo or whatever you're using for error handling
}
?>
上面的示例充斥着 SQL 注入。当然,验证和消毒。同样,从 PHP 5.5 起 mysql_query 函数将被弃用,因此请掌握使用mysqli_query 函数的窍门。更好的是,看看你是否可以使用PDO。:)