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:

<?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?

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.

Thanks!

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

?>

Answer by Starx

You dont need to

session_id($_POST['session_id']);

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.

...

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