簡體   English   中英

如何使用 ajax 將新行插入數據庫表

[英]How to insert a new row into a database table with ajax

目前,我在網頁上有一組員工照片。 每個員工都有一張進出照片。 它們分別被命名為firstname_here.jpgfirstname_away.jpg

當我點擊一張照片時,它會在兩者之間切換。

這只是我們在接待處的縱向觸摸屏上放置的一個簡單的進出板。 當員工進來時,他們點擊他們的照片以顯示 firstname_here.jpg 圖像,當他們離開時再次觸摸照片會變為 firstname_away.jpg。

我用這個例子https://www.golangprograms.com/javascript-example-to-change-image-on-click.html

並制作了這個工作版本

<!DOCTYPE HTML>
<html>

<script>
function toggleImage(firstname) {
    var img1 = "http://localhost:8888/attendance/" + firstname + "_here.jpg";
    var img2 = "http://localhost:8888/attendance/" + firstname + "_away.jpg";
    var imgElement = document.getElementById(firstname);
    imgElement.src = (imgElement.src === img1)? img2 : img1;
    var checkstatus = imgElement.src;
    if (checkstatus.includes("away")) {
        var status = "check_out";
    } else {
        var status = "check_in";
    }
}

</script>
<img src="http://localhost:8888/attendance/david_away.jpg" id="david" onclick="toggleImage('david');"/>
<img src="http://localhost:8888/attendance/ada_away.jpg" id="ada" onclick="toggleImage('ada');"/>

</body>
</html>

現在,我想連接到本地 mysql 數據庫,這樣當員工單擊他們的圖像時,它會寫入firstnamestatuscurrent date 和 time

我用這篇文章來設置我的數據庫設計來代表員工簽到和簽出

我與數據庫的連接有效,我可以使用手動發送信息

$sql = "INSERT INTO Main (firstname, status)
        VALUES ('John', 'check_in')";

我確實出於我的目的更改了我的字段,並且日期和時間是自動生成的。

幫助我知道 PHP 是基於服務器的,首先運行,javascript 是客戶端。 我瀏覽了這么多 stackoverflow 頁面,當有人單擊圖像時,我很難弄清楚如何寫入 mysql 數據庫。

我想寫名字和狀態變量。

如果您查看代碼所在的位置

if (checkstatus.includes("away")) {
    var status = "check_out";
        } else {
    var status = "check_in";
        }

You can insert a call (ajax for example) to a URL on your server that has a PHP script which contains the MySQL query that you mentioned, since you clearly know at that point in your javascript whether the user is checking in or checking out.

我會提到您當前修改狀態的解決方案有點可疑。 例如,如果多個人的名字相同,會發生什么? 應該使用某種 ID。

首先,我想我會調整你的圖像的目錄結構,這樣你就可以享受更簡單的編程和更容易的服務器維護。

attendance
    ada
        here.jpg
        away.jpg
    david
        here.jpg
        away.jpg

這使得相應子目錄中的所有文件名都相同/可預測。

當員工離開公司時,您只需刪除員工目錄即可刪除圖像。 將其與單獨搜索出勤目錄中的文件進行比較。

理想情況下,您應該為每個人使用數字 ID,這樣您就不會遇到名稱沖突。 最專業的是,您應該有一個員工數據庫表,當他們第一次注冊到您的系統時,他們被分配了一個 AUTOINCREMENTed id,然后在任何地方都使用該數字 id。

使用 class 切換技術並將圖像處理移動到 css 以獲得更清晰的 html 標記。

<div id="david" class="tapInOut here"></div>
<div id="ada" class="tapInOut away"></div>

請注意,在頁面加載時,您應該查詢您的數據庫以查看各自的員工當前是否在當天簽入或簽出。

在.css文件中:

.tapInOut {
    width: 200px;
    height: 200px;
}
#ada.here {
    background-image: url("attendance/ada/here.jpg");
}
#ada.away {
    background-image: url("attendance/ada/away.jpg");
}

將內聯單擊事件移動到 external.js 文件。 我已經很久沒有寫一個簡單的 js ajax 調用了,但是這個未經測試的塊應該讓你非常接近。

let togglables = document.getElementsByClassName("tapInOut"),
    checkInOut = function() {
        let http = new XMLHttpRequest(),
            params = 'firstname=' + this.id
                + '&status=' + (this.classList.contains('here') ? 'out' : 'in');
        http.open('POST', 'checkinout.php', true);
        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        http.onreadystatechange = function() {
            if (http.readyState == 4 && http.status == 200) {
                if (http.responseText === 'Success') {
                    this.classList.toggle('here');
                    this.classList.toggle('away');
                }
                alert(http.responseText);
            }
        }
        http.send(params);
    };

for (let i = 0; i < togglables.length; ++i) {
    togglables[i].addEventListener('click', checkInOut, false);
}

您甚至可能希望對可點擊圖像進行調暗、隱藏、禁用等操作,直到 ajax 響應,以便用戶知道程序正在處理請求。

至於接收.php腳本...

<?php
if (!isset($_POST['firstname'], $_POST['status']) || !ctype_alpha($_POST['firstname']) || !in_array($_POST['status'], ['here', 'away'])) {
    // you may want to validate the firstname against the db for best validation
    exit('Missing/Invalid Data Received');
}
$mysqli = new mysqli("localhost", "root", "", "myDB");
$query = "INSERT INTO Main (firstname, status) VALUES (?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $_POST['firstname'], $_POST['status']);
if ($stmt->execute()) {
    exit('Insert Failed');
}
exit('Success');

那么為什么我沒有在查詢中傳遞當前日期時間呢?

最干凈/最專業的技術是將您的Main (我真的認為這應該是employee_status_logs )表更改為CURRENT_TIMESTAMP的 DEFAULT 值。 這樣,每次插入新行且未聲明 datetime 列值時,db 都會自動為您將當前 datetime 寫入該行。

對於冗長的答案和建議對您的腳本進行大修感到抱歉,但是有很多技術可以推薦。 如果我犯了錯誤,請給我留言,以便我改進我的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM