March 19, 2012

Using same session ID in ajax can't connect to MySQL DB

Question by jeffery_the_wind

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:




$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'@'' (using password: YES) in /ajax_script.php on line 6, referer:

Does anyone know why I cannot connect like this?

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.


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



$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);


Answer by Starx

You dont need to


Just session_start() is enough

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!