Jump to content

serialize the object and save in database


chaiwei

Recommended Posts

Hi,

 

I have a class, example bear,

 

class bear {
  private $name;
  private $age;

  function __construct($name , $age){
    $this->name = $name;
    $this->age = $age;
  }

  function save(){
    sql = 'INSERT INTO xxx';
  }

}

$daddyBear = new bear('daddybear' , '1');
$daddyBear->save();

 

If I have a bear table, example

id -> (int) auto increment

name -> (varchar)

age -> (int)

 

should I add a object? ( used to save the bear class so when the time I fetch the data from database I don't have to assign again the name)

 

example:

class bear {
  private $name;
  private $age;

  function __construct($name , $age){
    $this->name = $name;
    $this->age = $age;
  }

  function save($class){
   sql = 'INSERT INTO {bear}( name, age, object) VALUES( "'.$this->name.'" ,  '.$this->age.' , "'.$class.'" )';
  } 
}

$daddyBear = new bear('daddybear' , '1');
$daddyBear->save(serialize($daddyBear));

$sql = 'SELECT * FROM bear';

while($xxx = mysql_fetch_array(xxx)){
    $bear[] = unserialize($xxx['object']);
}

echo $bear[0]->name;

 

Wouldn't It be easier? so I can use all the attribute again without have to set the attribute.

Is there any problem with my idea that I might miss out?

Please advice. Thanks.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.