1 回答

TA貢獻1801條經驗 獲得超16個贊
當您尋求 SQL 解決方案時,這實際上更多的是應用程序/業務需求,而不是數據庫問題。如果應用程序的業務邏輯需要限制用戶創建的記錄,那么應用程序應該查詢現有的記錄數量并向用戶提供適當的消息傳遞。
從插入 SQL 中看不出來插入到表中的行是否tasks
包含用于標識哪個用戶輸入它的列。如果這是一個單用戶應用程序,或者您的底層框架可能會自動處理此問題,那么這可能沒問題。task
如果這兩個都不成立,我們需要在該表中添加一列來捕獲用戶 ID 或其他標識信息,以便將每條記錄與其各自的用戶關聯起來(例如,根據您的用例、IP 地址或會話 ID)可能就足夠了)。
假設上述全部成立,我們應該實施一些更改:
切勿向用戶顯示表單,因為這會提供不支持/不允許的功能。相反,我們將用消息替換表單,以向用戶提供適當的反饋。
如果我們收到
POST
用戶在超出限制后嘗試添加新記錄的請求,請拒絕該請求并向用戶顯示一條消息。將一
userId
列或一些數據添加到表中以將用戶關聯起來tasks
。插入 new 時設置此新列的值
tasks
。
無論是 aGET
還是POST
,我們都希望在渲染頁面之前查詢用戶的現有記錄。
<?php
$errors = "";
$maxUserTasks = 7;
$db = mysqli_connect("localhost", "root", "", "certanet");
// Before even handling the request, query for the user's existing records
$sql = "SELECT task FROM tasks WHERE userId = 123"
$userTaskCountQuery = mysqli_query($db, $sql);
$userTaskCount = $userTaskCountQuery->num_rows();
if (isset($_POST['submit'])) {
if (empty($_POST['task'])) {
$errors = "";
}else if ($userTaskCount > $maxUserTasks){
$errors = "You already have $maxUserTasks tasks."
}else{
// Here is where you'll first want to check
$task = $_POST['task'];
$sql = "INSERT INTO tasks (task) VALUES ('$task')";
mysqli_query($db, $sql);
header('location: dashboard.php');
}
}
// Presumably, your page markup and form are somewhere down here
if ($userTaskCount > $maxUserTasks){
// display our error message here
}else{
// otherwise, display our form
}
?>
- 1 回答
- 0 關注
- 125 瀏覽
添加回答
舉報