query mysql database from inside a class

2019-04-12 00:14发布

I'm trying to run a query to a MySQL database from within a class and it's not working for some reason. I have the class in a separate file which I'm linking to with the require_once() function.

here's what the main .php file looks like:

<?php
  require_once("connect.php");
  require_once("theClass.php");

  $a = new theClass;
  $a->runQuery();
}

connect.php:

<?php
//connect to mySQL database
$mysqli = new mysqli("host", "user", "password", "db");
if ($mysqli->connect_errno)
{
    echo "<br><h1>Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error . "</h1><br>";
}

theClass.php:

<?php
require_once('connect.php');

class theClass
{
  //class variables and other functions here

  function runQuery()
  {
    $query = "SELECT col_1 FROM db.table";
    $stmt = $mysqli->prepare($query);
    stmt->execute();
    $stmt->bind_result($r);

    while($stmt->fetch())
    {
      echo $r . "<br>";
    }
  }
};

I've tried copying the class into the main .php file and it still doesn't work; however, I have used the exact same code( the query, prepare, execute, bind_result, and fetch part) in an external .php file as well as inside the main .php file and it has worked both times. This leads me to believe that you're not able to run queries from inside a class or that there is a different way of going about doing so. Could anyone point me in the right direction?

Thanks

2条回答
可以哭但决不认输i
2楼-- · 2019-04-12 01:06

Pass it to the method itself

You have to pass the database object to the method, because they are not in the same scope:

function runQuery($mysqli)

and call it like

$a = new theClass;
$a->runQuery($mysqli);

Pass it to the constructor

If your class makes a lot of database calls, you could simply pass it in the constructor and save it as a private variable for later use:

class theClass
{
  private $mysqli;

  function __construct($mysqli) {
    $this->mysqli = $mysqli;
  }

  function runQuery()
  {
    $query = "SELECT col_1 FROM db.table";
    $stmt = $this->mysqli->prepare($query);
    stmt->execute();
    $stmt->bind_result($r);

    while($stmt->fetch())
    {
      echo $r . "<br>";
    }
  }
};

and call it like

$a = new theClass($mysqli);
$a->runQuery();

Both methods make it clear that the dependency of your class is a mysqli object, which is good for future maintenance and readability.

查看更多
虎瘦雄心在
3楼-- · 2019-04-12 01:13

You need to either pass $mysqli as a parameter or use global $mysqli

<?php
require_once('connect.php');

class theClass
{
  //class variables and other functions here

  function runQuery()
  {
    global $mysqli;
    $query = "SELECT col_1 FROM db.table";
    $stmt = $mysqli->prepare($query);
    stmt->execute();
    $stmt->bind_result($r);

    while($stmt->fetch())
    {
      echo $r . "<br>";
    }
  }
};
查看更多
登录 后发表回答