Store variables from MySQL select to PHP class var

2019-08-01 16:39发布

问题:

I am selecting data from a database. The database field names are exactly the same as the class variable names. Is there a way to store this data into the class variables without specifying each one individually?

    //gets info about a specified file.
    //chosen based on a supplied $fileId
    function getFileInfo($fileId)
    {
        //select info from database
        $sql = "SELECT id, companyId, url, name, contentType, fileSize, saved, retrieved
                FROM files
                WHERE id = $fileId";
        $results = $this->mysqli->query($sql);
        $results = $results->fetch_object();

        //store info into class variables
        $this->id = $results->id;
        $this->companyId = $results->companyId;
        $this->url = $results->url;
        $this->name = $results->name;
        $this->contentType = $results->contentType;
        $this->fileSize = $results->fileSize;
        $this->saved = $results->saved;
        $this->retrieved = $results->retrieved;
    }

回答1:

I'd propose this approach:

$nameMap = array(
   'id',
   'companyId',
   'url',
   'name',
   'contentType',
   'fileSize',
   'saved',
   'retrieved',
);

foreach( $nameMap as $attributeName ) {
   $this->$attributeName  = $results->$attributeName ;
}

While one could write

foreach($result as $var => $value) {
...
}

the outcome fully depends on backing table's structure. If you add further attributes to the table, your code might break.

Using $nameMap, the application still works.



回答2:

A quick and dirty way would ba a loop:

foreach($result as $var => $value) {
    $this->$var = $value;
}


回答3:

Just use foreach structure:

foreach ($result as $column => $value) {
  $this->$column = $value;
}

Not nice but will work.



回答4:

Humm. Well, PDO has native functions for that, if you're not married to mysqli for some reason:

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;

The biggest disadvantage I've found is that PDO doesn't support SSL connections between the PHP machine and the MySQL machine.



标签: php oop mysqli