从一个类里面查询mysql数据库 [英] query mysql database from inside a class

查看:128
本文介绍了从一个类里面查询mysql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个类中运行查询MySQL数据库,它不工作的原因。我有一个单独的文件中的类,我链接到 require_once()函数。

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.

主要的.php文件如下:

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:

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:

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>";
    }
  }
};

我试过将类复制到主.php文件,它仍然不工作;然而,我已经使用完全相同的代码(查询,准备,执行,bind_result和fetch部分)在外部.php文件以及主.php文件内,它已经工作了两次。这导致我相信,你不能在类中运行查询或有一个不同的方式去这样做。任何人都可能指向正确的方向?

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?

感谢

推荐答案

将其传递给方法本身



您必须将数据库对象传递给方法,因为它们不在同一范围内:

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)

并像

$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>";
    }
  }
};

并调用

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






两种方法都清楚地表明,类是一个mysqli对象,这对于未来的维护和可读性是有好处的。


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

这篇关于从一个类里面查询mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆