为PHP用户类创建mySQLi准备的语句

时间:2018-09-29 08:10:05

标签: php mysqli prepared-statement

我创建了一个User类,它看起来像这样:

class User {
    private $user;
    private $con;

    public function __construct($con, $user){
        $this->con = $con;
        $user_details_query = mysqli_query($con, "SELECT * FROM users WHERE username='$user'");
        $this->user = mysqli_fetch_array($user_details_query);
    }

    public function getUsername() {
        return $this->user['username'];
    }

    public function getNumberOfFriendRequests() {
        $username = $this->user['username'];
        $query = mysqli_query($this->con, "SELECT * FROM friend_requests WHERE user_to='$username'");
        return mysqli_num_rows($query);
    }

    public function getNumPosts() {
        $username = $this->user['username'];
        $query = mysqli_query($this->con, "SELECT num_posts FROM users WHERE username='$username'");
        $row = mysqli_fetch_array($query);
        return $row['num_posts'];
    }

还有很多,但是我想了解的是如何使用准备好的语句重新创建它,而不会弄乱其余页面。我有多个页面的调用,这些页面依赖于给定的User类构造。我不熟悉准备的演出,但是成绩不错,但是在上课时遇到了麻烦。我尝试重新创建例如public function getNumberOfFriendRequests(),以使其具有与以前相同的输出,以便现有页面不会引发错误。这是我到目前为止的内容:

public function getNumberOfFriendRequests() {
$username $this->user['username'];
$query = mysqli_prepare($this->$con, "SELECT COUNT(*) FROM friend_requests WHERE user_to=?");
$query->bind_param('s', $username);
$query->execute();
$query_>bind_result(NOT SURE);
$query->fetch();
}

我也对public function __construct($con, $user)感到困惑,因为每当我要访问用户数据时都会调用该名称。有谁知道我将如何开始重写给定的User类,以使返回值相同且不会干扰从属页面上的php调用?

1 个答案:

答案 0 :(得分:1)

这应该是您使用重写语句编写的同一类。您说“此用户”并传递数据库对象时,您的构造很有意义。您不会像使用SELECT *那样使用bind_result,bind_result用于定位特定字段。

String test = String.format(Locale.US, "%, d", 1000000000);

or

Locale.setDefault(Locale.US);
String test = String.format("%, d", 1000000000);

P.S。不要使用SELECT *;参见:Select * Is Evil