The best way to turn a MySQL query into an object

I have a user table that contains a bunch of columns that I want to get in the mysql query for the logged in user. Ultimately, I want the values ​​in these columns to form a User object. Is there a standard function for this, or do I basically need to pass each request value to a new User statement so that they are passed to the constructor of the User class?

+3
source share
3 answers

mysql_fetch_object() allows you to specify the name of the class, so instances of this class will be built from your results:

$result = mysql_query($sql); // Error handling not included

if (mysql_num_rows($result) == 1) {
    $user = mysql_fetch_object($result, 'User');
}

If you do not specify properties and their access modifiers corresponding to the columns listed in your query SELECT, they will be by default public.

. , , .

+5

mysqli_result::fetch_object. PHP PDO.

.

CREATE TABLE `user` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(256) NOT NULL,
    `password` VARCHAR(256) NOT NULL,
     PRIMARY KEY (`id`)
);

. - , public , , ; . , .

class User {
    private $id;
    private $username;
    private $password;

    public function __construct($id, $username, $password) {
        $this->id = $id;
        $this->username = $username;
        $this->password = $password;
    }

    public function getId() { return $this->id; }
    public function setId($id) { $this->id = $id; }

    public function getUsername() { return $this->username; }
    public function setUsername($username) { $this->username = $username; }

    public function getPassword() { return $this->password; }
    public function setPassword($password) { $this->password = $password; }
}

Query

. - , .

class UserQuery {
    public function create() {
        return new self();
    }

    public function findById($id) {
        $user = null;
        $conn = mysqli_connect("localhost", "root", "pass", "company_db");

        if ($conn->connect_error)
            die("$conn->connect_errno: $conn->connect_error");

        $query = "SELECT * FROM `user` WHERE `id` = ?";
        $stmt = $conn->stmt_init();

        if (!$stmt->prepare($query)) {
            print "Failed to prepare statement\n";
        } else {
            $stmt->bind_param('i', $id); 
            $stmt->execute();
            $result = $stmt->get_result();
            $obj = $result->fetch_object();

            return new User($obj->id, $obj->username, $obj->password);
        }

        $stmt->close();
        $conn->close();

        return null;
    } 
}

User User.

$user = UserQuery::create()->findById(1);
printf("Found user: %s", $user->getUsername());
+1

Source: https://habr.com/ru/post/1785683/


All Articles