您好,我目前有一个网站,上面有一个运行着node.js的游戏。它包括gulp和socket.io。
我有一个要从node.js调用的php文件,它返回成功消息(文件中回显),但不更新数据库。
但是,当我通过将链接放在浏览器中或从我的网站使用相同的AJAX命令调用该php文件时,它运行得很好。
因此从我的网站:site.com,该php文件运行正常,但是从我的节点服务器:site.com:3000,它返回了成功,但没有更新我的数据库。
我知道Node与php不兼容,但是也许有解决方法。
我还注意到从节点调用文件时,变量为空。
这是我的php文件:
subtract5.php
<?php
header('Access-Control-Allow-Origin: http://cashballz.net:3000', false);
include 'mysql.php';
session_start();
$cash_amount = $_SESSION['cash_amount'];
$userid = $_SESSION['id'];
$_SESSION['cash_amount'] -= 0.05;
$mysql = new Mysql();
$result = $mysql->setCashAmount($cash_amount,$userid);
if($result)
{
echo "5 cents have been subtracted!";
}
else
{
session_start();
session_unset();
session_destroy();
}
?>
mysql.php
<?php
class Mysql
{
protected $dsn;
protected $username;
protected $password;
public $db;
function __construct()
{
//change this to your info (myDBname, myName, myPass)
$this->dns= 'mysql:dbname=cashball_accounts;host=localhost;charset=utf8';
$this->username= 'cashball_root';
$this->password= '1VeryBright*';
$this->db = new PDO($this->dns, $this->username, $this->password);
}
public function setCashAmount($cash_amount, $id)
{
$sql = "UPDATE users SET cash_amount = :cash_amount - 0.05 WHERE id = :id";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':cash_amount', $cash_amount, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$result = $stmt->execute();
return $result;
}
}
?>
然后我的AJAX呼叫:(app.js)
//cut 5 cents from account - php function
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: {},
success: function (data) {
alert(data);
}
});
我需要一种方法来正确运行我的PHP脚本并直接从node.js更新我的数据库。我已经在github上看到了文件解决方案,但是我不知道这是正确的解决方案还是如何在我的代码中实现它们。也许有一种方法可以在后台使用Ajax通过不同的域来调用php文件?
我是PHP的初学者,并且在JS方面不错,所以请详细说明您的答案。
感谢您的帮助!
答案 0 :(得分:0)
所以我想知道
$offer->users
从Node调用时,sql语句将是什么?您可以调试吗(从Node调用时)
我的猜测是
$result = $stmt->execute();
从节点调用时为空
答案 1 :(得分:0)
正如您在评论中所述,$_SESSION
变量为空。假设您在node.js中拥有相同的数据(id和现金量),则可以将其与AJAX调用一起传递,如下所示:
//cut 5 cents from account - php function
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: {
'id' : 'someid_probablyasint',
'cash_amount' : 'someamount_probablyasint'
},
success: function (data) {
alert(data);
}
});
然后,您可以访问php文件中由于$_POST
而通过type: "POST"
传递的变量。遵循以下原则:
<?php
header('Access-Control-Allow-Origin: http://cashballz.net:3000', false);
include 'mysql.php';
$cash_amount = $_POST['cash_amount'];
$userid = $_POST['id'];
$new_cash_amount = $cash_amount - 0.05;
$mysql = new Mysql();
$result = $mysql->setCashAmount($cash_amount, $userid);
if ($result) {
echo json_encode([
'new_cash_amount' => $new_cash_amount,
'message' => '5 cents have been subtracted!'
]);
} else {
echo json_encode(['error' => 'Huge error.']);
}
?>