[英]When I store a javascript variable in mysql, how does it get linked to the current user's id?
Let's say there is a site that has a button that uses javascript to increase the value of the javascript variable "javascriptx" by +1 each time it is clicked. 假设有一个站点带有一个按钮,该按钮每次使用时都使用javascript将javascript变量“ javascriptx”的值增加+1。 UserA (id=1 on the MySql table) logs in to the website and presses the button 3 times, so javascriptx = 2.
UserA(MySql表上的id = 1)登录到网站并按3次按钮,因此javascriptx = 2。
The next time UserA logs in, I want javascriptx to still equal 2 (assuming the button hasn't been pressed any more times), so I need to convert that javascript variable to a php variable and send it to MySql. 下次UserA登录时,我希望javascriptx仍等于2(假设尚未再次按下按钮),因此我需要将该javascript变量转换为php变量并将其发送到MySql。 As far as I understand, this is the correct way to do that:
据我了解,这是正确的方法:
Add the following to the javascript code: 将以下内容添加到javascript代码中:
var xhr = new XMLHttpRequest();
xhr.open("get","/path/to/php/page.php?phpx=javascriptx");
xhr.send();
Now, the php variable "phpx" has the same value as the javascript variable "javascriptx" 现在,php变量“ phpx”具有与javascript变量“ javascriptx”相同的值
Then, that php variable needs to be sent to the MySql table, so the following is added to the php code: 然后,该php变量需要发送到MySql表,因此将以下内容添加到php代码中:
($_GET['phpx'])
From here, I get lost. 从这里,我迷路了。 Where does phpx get stored in the MySql table?
phpx哪里存储在MySql表中? More specifically, how does it know to put this in the same row as user with id=1?
更具体地说,如何知道将其与id = 1的用户放在同一行?
You should connect to the MySQL database using something like mysqli : 您应该使用mysqli之类的东西连接到MySQL数据库:
$database = new mysqli(db_host, db_username, db_pass, db_name);
Then you can make queries to your database with prepared statements to read/write data. 然后,您可以使用准备好的语句对数据库进行查询以读取/写入数据。 In this rough example, the data will return a JSON response to your web application or wherever you make the request from:
在此粗略示例中,数据将返回JSON响应到您的Web应用程序,或者无论您从何处发出请求:
//set user id from post variable
$uid = $_POST['uid'];
//store sql query as string
$sql = "SELECT phpx FROM users WHERE uid=?";
//initiate new prepared statement
$stmt = $database->stmt_init();
$stmt->prepare($sql);
//pass uid var to statement
$stmt->bind_param('s', $uid);
//store result as var
$stmt->bind_result($phpx);
$stmt->execute();
//catch errors
if ($stmt->errno) {
die("error: " . $stmt->error);
} else {
//store result and send as response
$stmt->store_result();
if($stmt->num_rows){
while($stmt->fetch()){
$phpx_packet[] = array(
"uid" => $uid,
"phpx" => $phpx
);
}
echo json_encode($phpx_packet);
}
}
//close statement
$stmt->close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.