尝试调用函数时,出现以下错误:
Fatal error: Call to a member function prepare() on a non-object in /var/www/includes/functions.php on line 32
我正在使用以下代码从另一个页面调用此函数:
if (login($email, $password, $mysql) == true) {
// Login success
header('Location: ../home.php');
} else {
// Login failed
header('Location: ../error.php?error=1');
}
下面是该函数的代码:
function login($email, $password, $mysql) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysql->prepare("SELECT id, password, salt //Line 32
FROM members
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
我阅读了其他问题,看了anwsers,通过阅读这些内容,我相信$ mysql变量是问题所在。
我尝试在我的functions.php的顶部添加以下代码,但仍得到相同的结果:
global $mysql
在我的functions.php页面上,我还有以下代码行:
include ("db_connect.php");
db_connect.php包含以下内容:
<?php
include_once 'db_config.php'; // Database information
$mysql = mysql_connect(HOST, USER, PASSWORD, DATABASE);
?>
global
应该在功能范围内使用,而不是在功能范围之前/之前使用。
function myfunc(){ // Do NOT pass anything called $mysql to this function!
global $mysql;
do_stuff_with_mysql();
}
当然,必须在声明函数(在db_connect.php
文件中)之前定义它:
$mysql = new PDO($dsn, $user, $pass);
参见:http : //fr2.php.net/manual/en/language.variables.scope.php。另外,您可能要考虑面向对象的编程:
class DB {
private $pdo;
public function __construct() { $this->pdo = new PDO(...); }
public function myfunction() { /* use $this->pdo here */ }
}
重要说明: mysql_*
现在不推荐使用功能。http://www.php.net/manual/zh/book.pdo.php
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句