【问题标题】:How to set "set_charset('utf8');" for the entire class:如何设置“set_charset('utf8');”对于整个班级:
【发布时间】:2013-07-23 13:05:30
【问题描述】:

您好,我知道如何设置“set_charset('utf8');”与风格:

$db = new mysqli('127.0.0.1','root','pass','data') or die ('error with connection');
$db->set_charset('utf8');

但现在我想用这样的类来做到这一点:

class Core {
protected $db, $result;
private $rows;

public function __construct(){
    $this->db = new mysqli('127.0.0.1','root','pass','data');

    }

public function query ($sql){
    $this->result = $this->db->query($sql);
    }

public function rows(){
    for($x =1; $x<= $this->db->affected_rows; $x++){
        $this->rows[] = $this->result->fetch_assoc();
        }
        return $this->rows;
    }
}

但我无法创建这个 db set charset 部分,它总是出现某种错误:)

请帮忙, 谢谢

【问题讨论】:

  • 究竟是什么错误?
  • 发布的代码没有错误,它工作正常。问题是当我尝试插入“set_charset('utf8');”部分。如果我在$this-&gt;db = new mysqli('127.0.0.1','root','pass','data'); 下尝试:$this-&gt;set_charset('utf8'); 它会给我“致命错误:调用未定义的方法 Homepage::set_charset()”

标签: php database class character-encoding


【解决方案1】:

您的代码运行良好,但在您的评论中我发现了一个错误。

试试这个解决方案:

class Core extends mysqli
{
    protected $db, $result;
    private $rows;

    public function __construct()
    {
        parent::__construct('127.0.0.1','root','pass','data');

        if (mysqli_connect_error()) {
            throw new exception('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
        }

        $this->set_charset('utf-8');
    }


    public function query($sql)
    {
        $this->result = parent::query($sql);
    }
}

当您将 Core 类调用为 Object 时,将自动创建与数据库的连接,并将设置字符集 UTF-8。

MySQLI 类被扩展以重用您的所有方法,例如 $core_class_object->stmt_init();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多