How to put session into database

  • 2020-06-07 04:09:24
  • OfStack

php's session is saved as a file by default. In php's configuration file, php.handler ="files", we can see a line like this: session.save_handler ="files". This is just to show that we are not storing session as a file. We also need to select the database and create the table for the database.

To establish a database and database table structure, we can use php can use any database, because of the combination of php and mysql is best, I'll use mysql for example, according to your needs can be renamed other database, of course, because no things mysql function at the same time, this also is faster than other database, but save session books, 1 don't want to deal with things, moreover, I definitely better.
Create database:

CREATE DATABASE 'session';  Create table structure  CREATE TABLE 'session'( id CHAR(30) NOT NULL  , 'user 'CHAR(30), data CHAR(3000) ,PARMIRY BY ('id') );

Let's write es28EN_start.php to save session

<?php
 $con =mysql_connection("127.0.0.1","user" , "pass");
        mysql_select_db("session");
function open($save_path, $session_name) 
{
    return(true);
}
function close() 
{
  return(true);
}
function read($id) 
{
   if($result = mysql_query("SELECT * FROM session WHERE id='$id'"))
     {
        if($row = mysql_felth_row($result ))
           {  return $row["data"]; }
      }
   else
     {
      return "";
      }
}
function write($id, $sess_data) 
{
  if($result = mysql_query("UPDATE session SET data='$sess_data' WHERE id='$id'"))
     {
        return true;
      }
   else
     {
      return false;
      }
}
function destroy($id) 
{
 if($result = mysql_query("DELETE * FROM  session WHERE id='$id'"))
     {
        return true;
      }
   else
     {
      return false;
      }
}
/*********************************************
* WARNING - You will need to implement some *
* sort of garbage collection routine here.  *
*********************************************/
function gc($maxlifetime) 
{
  return true;
}
session_set_save_handler("open", "close", "read", "write", "destroy", "gc");
session_start();
// proceed to use sessions normally
?>

Now we are done, as long as you need to use session, es35EN_ES36en_start.php. I'm going to include,
Note that this file 1 must be included in line 1 of the file, and then you want to use the file's session1-like methods.

Related articles: