无法将我的 MySqli 连接到我的其他类


Can't connect my MySqli to my other classes

我的连接:

  <?php
    $db = new mysqli('localhost', 'root', '', 'audiologiska_kliniken');
    if($db->connect_errno > 0){
        die('Ett fel inträffade [' . $db->connect_error . ']');
    }

我的班级:

  <?php
//Display model
require '../include/connect.php';
Class Display
{

    function getData() {
        mysql_set_charset('utf8');
        if($result =$db->query= "SELECT * FROM patient left join person on person.Personnummer = Patient.Patient";`enter code here`

问题:类无法识别$db。为什么?

因为你没有将变量$db传递给你的函数,(它不在函数范围内)

将您的函数更改为以下内容:

function getData($db){

以及您的函数对此的调用:

getData($db);

这应该对你有用。

这个问题是因为变量的作用域:你看不到函数内部全局数据中的变量。你可以修改你的函数getData():

function getData() {
    global $db;
    mysql_set_charset('utf8');
    if($result =$db->query= "SELECT * FROM patient left join person on person.Personnummer = Patient.Patient";`enter code here`

但这种方法并不是"最好的"。更好的方法 - 为您的类添加连接,即:

require '../include/connect.php';
Display::$connection = $db;
Class Display
{
static $connection;
function getData() {
    mysql_set_charset('utf8');
    if($result =self::$connection->query= "SELECT * FROM patient left join person on person.Personnummer = Patient.Patient";`enter code here`
相关文章: