class User{
public $id, $username, $firstname, $lastname;
public function find(){
$result = blabla->query('SELECT * FROM users WHERE id = 1');
return $result;
}
}
我很有兴趣如何将值(来自mysql)分配给类变量。
$user = new User();
$user->find();
echo $user->username;
echo $user->lastname;
答案 0 :(得分:0)
我不确定它是否适用于SELECT *
,但您可以尝试PDO::FETCH_INTO
:
class User{
public $id, $username, $firstname, $lastname;
public function find(){
$result = blabla->query('SELECT id, username, firstname, lastname FROM users WHERE id = 1');
$this = $result->fetch( PDO::FETCH_INTO );
}
}
如果不起作用,您可以使用bindColumn
call with PDO::FETCH_BOUND
选项:
class User{
public $id, $username, $firstname, $lastname;
public function find() {
$result = blabla->query('SELECT id, username, firstname, lastname FROM users WHERE id = 1');
$result->bindColumn( 1, $this->id );
/* Other bindColumn calls here */
return $result->fetch( PDO::FETCH_BOUND );
}
}
答案 1 :(得分:0)
您可以尝试这样做:
class User{
public $id, $username, $firstname, $lastname;
public function find () {
$result = blabla->query('SELECT * FROM users WHERE id = 1');
$this->id = $result['id'];
$this->username = $result['username'];
$this->firstname = $result['firstname'];
$this->lastname = $result['lastname'];
}
}