在ajax中使用相同的会话ID无法连接到MySQL DB [英] Using same session ID in ajax can't connect to MySQL DB

查看:95
本文介绍了在ajax中使用相同的会话ID无法连接到MySQL DB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个通用的PHP脚本来进行AJAX调用.我在SESSION变量中存储了用于mysql连接的用户名和密码.为了在此ajax脚本中启动相同的会话,我通过发布将会话ID传递给ajax脚本.变量已正确传递,我使用error_log检查了用户名和密码SESSION变量是否正确.这是ajax_script.php:

I have made a generic PHP script to use for an AJAX call. I have the username and password for the mysql connection stored in SESSION variables. In order to start the same session in this ajax script, I pass the session ID via post to the ajax script. The variables are being passed correctly and I checked using error_log that the username and password SESSION variables are the correct values. Here is the ajax_script.php:

<?php

session_id($_POST['session_id']);
session_start();

mysql_connect('10.X.X.X',$_SESSION['username'],$_SESSION['password']);

$results = mysql_query($_POST['query']);

echo json_encode($results);

?>

但是,无法建立连接.我检查了日志文件,这是错误:

However, the connection cannot be established. I checked the log file and this is the error:

 PHP Warning:  mysql_connect(): Access denied for user 'username'@'25.1.1.1' (using password: YES) in /ajax_script.php on line 6, referer: http://25.1.1.1/index.php?option=com_content&view=article&id=180

有人知道我为什么不能这样连接吗?

Does anyone know why I cannot connect like this?

以前,我制作了类似的脚本,但没有像上面那样引用session_id来启动相同的会话.我通过帖子传递了用户名和密码,并且连接正常.

Previously I made a similar script, but did NOT start the same session referencing the session_id like above. I passed user names and passwords via post, and the connection worked.

谢谢!

**编辑**对不起,我为mysql连接使用了错误的IP.以下代码有效:

** EDIT ** Sorry, I used the wrong IP for the mysql connection. the following code works:

<?php

session_start();

$ajax_connection = mysql_connect('10.X.X.X',$_SESSION['username'],$_SESSION['password']);

$result_set = array();

while ($result_set[] = mysql_fetch_assoc($results)){
    // do nothing
}

echo json_encode($results);

?>

推荐答案

您不需要

session_id($_POST['session_id']);

只需session_start()就足够了

也许您的会话即将结束.在两个页面上使用以下代码段

Maybe your session is expiring on close. Use the following snippet on both pages

session_cache_expire(30); //expire in 30 minutes

检查答案以获取有关会话到期的更多信息.

Check this answer for more information on session expiring.

这篇关于在ajax中使用相同的会话ID无法连接到MySQL DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆