0

I wrote a portal for my company that has dozens of ajax calls in it. For every ajax call, the target script uses mysql and session variables. on every one of those scripts I do:

page.php

    $.ajax({
            type:"POST",
            data:someData,
            url:target.php,
            success:function(result){
                    someAction
            }
    });

target.php

   <?php
      session_start(); 
      //target from ajax.php
      require_once('/var/www/lib/db.php');
       ......
       ......
        $_SESSION['someVar'] = $someMysqlResult;

db.php

  $db = new PDO('mysql:host=localhost;dbname=someDB', 'someUser', 'somePassword');

so I am setting up new mysql connections dozens of times. Is there a better way? Is there a mysql resource I can carry across all of these ajax calls?

I am also starting the session dozens of times. Is there a better way to open the session again on the target script?

bart2puck
  • 2,432
  • 3
  • 27
  • 53

1 Answers1

0

According to the documentation, you can use persistent connections:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

You should be aware that doing this though has some negative drawbacks to be aware of: What are the disadvantages of using persistent connection in PDO

Community
  • 1
  • 1
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133