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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.