调用非对象 PHP 帮助上的成员函数 prepare()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4463441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:06:35  来源:igfitidea点击:

Call to a member function prepare() on a non-object PHP Help

phpmysqliprepared-statement

提问by mcbeav

I am trying to write a PHP function. It is very simple. It is just a prepared statement that queries the database, but I can not get this to work. I keep recieving the error Call to a member function prepare() on a non-object. here is the code:

我正在尝试编写一个 PHP 函数。这很简单。这只是一个查询数据库的准备好的语句,但我无法让它工作。我不断收到错误 Call to a member function prepare() 在非对象上。这是代码:

$DBH = new mysqli("host", "test", "123456", "dbname");
function selectInfo($limit, $offset){
    $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
    }
selectInfo();

Any time I call the function i get that error. Can someone please help?

每当我调用该函数时,我都会收到该错误。有人可以帮忙吗?

回答by ircmaxell

It's a scoping error. You're making $DBHa global variable. So when you enter the function, the global variable is not available. You have 5 real options.

这是一个范围错误。您正在创建$DBH一个全局变量。所以当你进入函数时,全局变量是不可用的。您有 5 种实​​际选择。

1. Use the global keyword

1. 使用 global 关键字

function doSomething() {
    global $DBH;
    //...

This is not a good idea, since it makes maintenance and testing a PITA. Imagine trying to debug that function call. You now need to go find out where $DBHis defined to try to figure out what's going on...

这不是一个好主意,因为它使维护和测试成为 PITA。想象一下尝试调试该函数调用。您现在需要找出$DBH定义的位置以试图弄清楚发生了什么......

2. Make $DBHa parameter to the function

2.$DBH给函数做一个参数

function doSomething(MySQLi $DBH) {

It has the advantage of being explicit. But it's still not great since the calling code then needs to keep track of the global variable.

它的优点是明确。但这仍然不是很好,因为调用代码需要跟踪全局变量。

3. Create a function to "get" the $DBHobject

3.创建一个函数来“获取”$DBH对象

function getDBH() {
    static $DBH = null;
    if (is_null($DBH)) {
        $DBH = new mysqli(...);
    }
    return $DBH;
}

function doSomething() {
    $DBH = getDBH();
}

This has the advantage of getting around the global variable problem completely. But it's also hard to have multiple connections or re-use any of the code for other connections.

这具有完全解决全局变量问题的优点。但是也很难有多个连接或将任何代码重用于其他连接。

4. Create a class to wrap database access

4.创建一个类来包装数据库访问

class Database {
    public function __construct($host, $user, $pass) {
        $this->DBH = new MySQli($host, $user, $pass);
    }
    public function doSOmething() {
        $this->DBH->foo();
    }
}

This encapsulates everything for you. All database access will go through a single class, so you don't need to worry about global variable access or anything else.

这为您封装了所有内容。所有数据库访问都将通过一个类,因此您无需担心全局变量访问或其他任何事情。

5. Use a pre-built class/framework

5. 使用预先构建的类/框架

This is the best option, since you don't need to worry about doing it yourself.

这是最好的选择,因为您不必担心自己做。

Database Access Classes:

数据库访问类:

Full Frameworks:

完整框架:

Really, the choices are endless. Find something you like, and stick with it. It really will make your life easier...

真的,选择是无止境的。找到你喜欢的东西,并坚持下去。它真的会让你的生活更轻松......

Good Luck!

祝你好运!

回答by Jim

$DBHis not in scope. You either want to define $DBHas global in the function:

$DBH不在范围内。您要么想$DBH在函数中定义为全局:

$DBH = new mysqli("host", "test", "123456", "dbname");
function selectInfo($limit, $offset){
    global $DBH;
    $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
}

or as ircmaxell pointed out in his excellent answer have a function which returns a static instance of $DBH.

或者正如 ircmaxell 在他的优秀回答中指出的那样,有一个函数可以返回$DBH.

回答by Crozin

That's simply. $DBHdoesn't exist within selectInfo()function. Variable defined in global scope won't be visible within function and vice-versa. Read more about variables scopeon manual pages.

那简直了。$DBH不存在于selectInfo()函数中。在全局范围内定义的变量在函数内不可见,反之亦然。在手册页上阅读有关变量作用域的更多信息。

How to solve it? Pass that variable as a argument of the function:

如何解决?将该变量作为函数的参数传递:

$dbh = new MySQLi(...);

function selectInfo(MySQLi $dbh, $limit, $offset) {
    $stmt = $dbh->prepare(...);
    ...
}

回答by madkris24

Make sure the connection is successful.

确保连接成功。

$DBH = @new mysqli("host", "test", "123456", "dbname");

if ($DBH->connect_errno) {
    die('Connect Error: ' . $DBH->connect_errno);
}

or

或者

$DBH = @mysqli_connect("host", "test", "123456", "dbname");

if (!$DBH ) {
    die('Connect Error: ' . mysqli_connect_errno());
}

回答by István Ujj-Mészáros

Try to add global $DBH;in the function, or add it to the function's parameters.

尝试global $DBH;在函数中添加,或者将其添加到函数的参数中。

回答by Sandeepan Nath

selectInfo($DBH);

function selectInfo($DBH,$limit, $offset){
    $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
    }

回答by Nami Hamiroo

Making $DBH global is not healthy... except that you can make your $DBH protected in class and set it to null.. and use it..

使 $DBH 全局化是不健康的...除了您可以在类中保护 $DBH 并将其设置为 null .. 并使用它..

回答by Nami Hamiroo

class PDOconnect extends PDO{

protected $con=null;

受保护的 $con=null;

    public function __construct(){
              try {      

                     $this->con= new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); //our new PDO Object

                      $this->con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );                       
                      $this->con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );                     
                      $this->con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                      echo "hi.. you are connected succcessfully...";
                  }