【问题标题】:How to insert a new row into a database table with ajax如何使用ajax在数据库表中插入新行
【发布时间】:2020-08-22 02:44:17
【问题描述】:

目前,我在网页上有一组员工照片。 每个员工都有一张进出照片。它们分别被命名为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 数据库,这样当员工点击他们的图片时 它写入名字状态当前日期和时间

我使用这篇文章来设置我的数据库 Design to represent employee check-in and check-out

我与数据库的连接正常,我可以使用手动发送信息

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

我确实为自己的目的更改了我的字段,并且日期和时间是自动生成的。

帮助 我知道 PHP 是基于服务器的,首先运行,而 javascript 是客户端。 我已经浏览了这么多 stackoverflow 页面,并且很难弄清楚当有人单击图像时如何写入 mysql 数据库。

我想写名字和状态变量。

【问题讨论】:

  • 只是好奇,这两张照片有什么不同?
  • 您不应该需要链接中的http://localhost:8888 部分。比如/attendance/david_away.jpg就足够了

标签: javascript php html mysql ajax


【解决方案1】:

如果你看看你的代码在哪里

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

您可以将调用(例如 ajax)插入到服务器上的 URL,该 URL 具有包含您提到的 MySQL 查询的 PHP 脚本,因为您在 javascript 中清楚地知道用户是否正在签入或退房。

我会提到,您当前修改状态的解决方案有点可疑。例如,如果多个人的名字相同,会发生什么?应该使用某种 ID。

【讨论】:

    【解决方案2】:

    首先,我想我会调整一下你的图片的目录结构,这样你就可以享受更简单的编程和更轻松的服务器维护。

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

    这使得相应子目录中的所有文件名相同/可预测。

    当员工离开公司时,您只需删除员工目录即可移除图像。将其与在考勤目录中单独搜索文件进行比较。

    理想情况下,您应该为每个人使用数字 ID,这样您就不会遇到名称冲突。最专业的是,您应该有一个员工数据库表,当他们第一次注册到您的系统时,他们被分配了一个 AUTOINCREMENTed id,然后任何地方都使用该数字 id。

    使用类切换技术并将图像处理移至 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");
    }
    

    将内联点击事件移至外部 .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。这样,每次插入新行且不声明 datetime 列值时,db 都会自动为您将当前 datetime 写入该行。

    对于冗长的答案和建议对您的脚本进行大修感到抱歉,但是有很多技术可以推荐。如果我犯了错误,请给我留言,以便我完善我的答案。

    【讨论】:

    • 感谢大家的帮助。不幸的是,我不得不搁置几天。我今天下午回来了。 @mickmackusa。 - 我将实施您的更改,包括文件层次结构并报告任何问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 2013-08-26
    • 2015-09-14
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多