javascript - 如何为登录用户读取和写入数据库数据
问题描述
我不知道真正读过这篇文章的人怎么会把它等同于“你如何在 PHP 中运行 WordPress 函数?”。我对在 PHP 中运行 WordPress 函数的兴趣为零。我的问题是关于识别提交 HTTP 请求的用户/会话。
确实,当您加载页面时,您可以使用 WordPress get_current_user_id() 函数来识别用户。但这并没有提出关于运行 WordPress 功能的问题。
我正在使用 WordPress、Javascript 和 PHP 构建一个站点。我有 PHP 脚本可以识别页面加载时登录的用户的 WordPress 用户 ID get_current_user_id()。但是,当我尝试通过 Javascript XMLHttpRequest 发送 HTTP 请求以执行 PHP 脚本时,PHP 文件无法识别来自 get_current_user_id() 的用户 ID。
我认为使用 PHP 会话会有所帮助,但他们没有。
那么,如何让用户写入数据呢?
解决方案
我发现 PHP 会话 ID 存储在 cookie 中。它在 cookie 字符串中显示为“...;PHPSESSID=fkldsjflksjlf;...”。在我的 Javascript XMLHttpRequest 脚本中,我使用以下内容从 cookie 中提取会话 ID。然后我将它作为参数发送。
function test() {
var idBegin = document.cookie.indexOf("PHPSESSID=") + 10;
var sessId = document.cookie.substring(idBegin)
var idEnd = sessId.indexOf(";");
sessId = sessId.substring(0, idEnd);
var request = new XMLHttpRequest();
request.open("GET", "test.php?sessid="+sessId, true);
request.onreadystatechange = function () {
if (request.readyState === 4) {
if ((request.status === 200) || (request.status === 0)) {
}
}
};
request.send(null);
}
在服务器端,我的 MySQL 数据库中有一个表“UserSessions”。该表有两列:SessionID;和用户 ID。我有一个在用户加载页面时执行的 PHP 脚本。此时,get_current_user_id() 函数可用于获取 WordPress 用户 ID,并且 $_COOKIE["PHPSESSID"] 可用。PHPSESSID 是作为 cookie 存储在客户端上的内容。
<?php
$sql = "INSERT INTO UserSessions (SessionID, UserID)";
$sql = $sql . " VALUES (" . $_COOKIE["PHPSESSID"] . ",";
$sql = $sql . get_current_user_id() . ")";
// I user the standard MySQLi stuff to execute the query and
// store the session ID, user ID pair
?>
在 PHP 中,我通过 Javascript 执行的脚本包括以下内容
<?php
$sql = "SELECT UserID FROM UserSessions ";
$sql = $sql . " WHERE SessionID = " . $_GET["sessid"];
// Again, standard MySQLi stuff to execute the query
// and retrieve the user id based on the session ID.
// I store the retrieved value in variable "$userid"
// When I have the user id, I can use it in other tables
// that have a UserID column
$sql = "SELECT column FROM table ";
$sql = $sql . " WHERE UserID = " . $userid;
$sql = "INSERT INTO table (column) VALUES (data) ";
$sql = $sql . " WHERE UserID = " . $userid;
?>
这似乎不是正确的方法。这个对我有用。而且我不知道如何做得更好。无论如何,告诉我这是不正确的,并给我正确的方法来做到这一点。谢谢。
推荐阅读
- r - 如何描述几个变量的分组观察的唯一值?
- python - 使用 Python pandas 提取嵌套的 JSON 数据
- java - 如何对 Java springboot 中的日志记录进行单元测试
- sql - 如何从日期列返回特定日期名称的数据
- javascript - 将 XML 响应转换为有用的数据
- ethereum - 以太坊区块头:recipientsRoot 的目的是什么?
- flutter - Flutter Textformfield如何在焦点丢失时调用onSubmitted或onEditingComplete
- java - 如何使用 youtube data api v3 登录
- javascript - 我想要输入文本/javascript,但它因“图像/gif”而失败
- pine-script - 松树:将系列整数转换为整数