Search code examples
phpmysqltransactionspdopersistent-connection

mysql pdo transaction and session storage


I have trouble deciding what would be the optimal solution for my web app, which is accessing (mainly reading) many times the same user data on every session.

Should I retrieve all user data at once (about 40 fields) to $_SESSION when opening a new session or should I keep a persistent PDO (mysql) connection and query just the parameters I need from the database on every script execution instead?

ALSO:

Would there be a big difference in performance between reading/updating a lot of fields at once (whith a custom query) or one by one (with a custom combination of generic queries) in the same transaction? e.g.

$dbh = new PDO("mysql:host=localhost;dbname",$dbuser,$dbpass,array(PDO::ATTR_PERSISTENT => true));

$fieldlist='';
foreach ($fields as $i=>$field){
    $fieldlist.=$field['name'].':field'.$i.',';
}
rtrim($fieldlist,',');
$dbh->prepare("UPDATE user SET ".$fieldlist." WHERE name=:name");
foreach ($fields as $i=>$field){
    $stmt->bindValue(':field'.$i, $field['value'], PDO::PARAM_STR);
}
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();

$dbh = null;

vs.

$dbh = new PDO("mysql:host=localhost;dbname",$dbuser,$dbpass,array(PDO::ATTR_PERSISTENT => true));


$dbh->beginTransaction();

foreach($fields as $field){
    $stmt=$dbh->prepare("UPDATE user SET ".$field['name']."=:field WHERE name=:name");
    $stmt->bindValue(':field', $field['value'], PDO::PARAM_STR);
    $stmt->bindValue(':name', $name, PDO::PARAM_STR);
    $stmt->execute();
}

$dbh->commit();

$dbh = null;

Solution

  • Cannot be done. Even if you could do this, it is a bad idea. You would create a situation with lots of concurrent open connections that would exceed your max connections.

    I am not sure why you have to continually update the session with the same data. Just put the data in the session one time, and be done.

    If you are dealing with a large data set, you may want to consider caching. This would reduce database load. You could use memcached. This will improve performance, it allows you to specify what and how many resources to cache.