我不确定这里出了什么问题。我刚刚在线阅读了一个教程,并且出现了这些错误。
我收到以下错误
错误
Notice: Undefined variable: db in C:\xampp\htdocs\wisconsindairyfarmers\admin\login.php on line 7
Fatal error: Call to a member function query() on null in C:\xampp\htdocs\wisconsindairyfarmers\admin\login.php on line 7
代码
<?php
$db = new mysqli('127.0.0.1', 'root', '', 'wisconsindairyfarmers');
?>
<?php
require '../db/connect.php';
require '../functions/general.php';
function user_exists($username){
//$username = sanitize($username);
$result = $db->query("SELECT COUNT(UserId) FROM users WHERE UserName = '$username'");
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
}}
if(empty($_POST) === false){
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) === true || empty($password) === true){
echo 'You need to enter a username and password';
}
else if(user_exists($username) === false) {
echo 'We can\'t find that username.';
}
}
?>
答案 0 :(得分:14)
首先,您在函数外声明了$ db。如果你想在函数中使用它,你应该把它放在函数代码的开头:
global $db;
我想,当你写道:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
你真正想要的是:
if ($result->num_rows==1) { return true; } else { return false; }
答案 1 :(得分:1)
将此行放在父结构中:$ this-&gt; load-&gt; database();
function __construct() {
parent::__construct();
$this->load->library('lib_name');
$model=array('model_name');
$this->load->model($model);
$this->load->database();
}
这样......它应该有效..