Ryan Deming Ryan Deming - 3 months ago 10
PHP Question

PHP use object to store other object into database PDO

I'm a bit lost trying to learn OOPHP. This isn't finalized code by any means, but I'm just trying to learn how I can store an object into the database using another object.

I read that I should convert the object being passed into an array, so I just typecast it, but I didn't want to use

class ObjectStorage {
private $myObject;

function __construct($object) {
$this->myObject = (array)$object;
}

function __get($attribute) {
return var_dump($this->$attribute);
}

public function saveVideo($conn) {
$sql = "INSERT INTO videos (`src`, `title`, `desc`, `cat_id`) VALUES (?, ?, ?, ?)";
$query = $conn->prepare($sql);
$query->execute($this->myObject);

echo "Video Saved!";
}


}

When running the get to see what's in myObject I get this

array(4) {
["Videosrc"]=>
string(4) "Test"
["Videotitle"]=>
string(5) "Title"
["Videodesc"]=>
string(4) "Desc"
["Videocat"]=>
string(3) "Cat"
}


I can't figure out how to access those. Could someone explain what I'm missing?

Answer

Something following should do

Just change your constructor if your database columns are named after object property names.

function __construct($object) {
    $bind = array();
    foreach($object as $prop => $val) {
        $bind[":$prop"] = $val;
    }
    $this->myObject = $bind;
}

In your example seems that your object props are with different name than database columns, so since PDO prepare array keys have to map database columns you could do something like this.

function __construct($object) {
    $bind = array();
    $bind[':src'] = $object->Videosrc;
    $bind[':title'] = $object->Videotitle;
    $bind[':desc'] = $object->Videodesc;
    $bind[':cat_id'] = $object->Videocat;
    $this->myObject = $bind;
}

And your INSERT query should look something like this

"INSERT INTO videos (`src`, `title`, `desc`, `cat_id`) VALUES (:src, :title, :desc, :cat_id)"
Comments