看,我有一个连接到mysql数据库的类,但我有另一个文件,其中包含用户名,主机,密码和表名,如果我不包含它并写它们,它工作正常,但是当我包含它时问题就开始了,它会返回我的#34;未定义的变量"。谢谢,这是我的班级:
<?php
include '../config/conexiongeneral.php';
class DbConnector {
var $theQuery;
var $link;
public function DbConnector(){
$host = $elnombredelhost;
$db = $labasededatos;
$user = $elnombredelusuario;
$pass = $lacontasena;
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
function fetchArray($result) {
return mysql_fetch_array($result);
}
function close() {
mysql_close($this->link);
}
}
?>
好吧,我忘记了我用以下方法调用此函数:
<?php
include 'dbConnector.php';
$connector = new DbConnector();
$username = trim(strtolower($_POST['username']));
$username = mysql_real_escape_string($username);
$query = "SELECT usuario FROM $latablatres WHERE usuario = '$username' LIMIT 1";
$result = $connector->query($query);
$num = mysql_num_rows($result);
echo $num;
mysql_close();
?>
答案 0 :(得分:4)
问题在于你将文件包含在类之外,因此它的范围是错误的(类不知道这些变量)。
试试这个:
public function DbConnector(){
include '../config/conexiongeneral.php';
$host = $elnombredelhost;
$db = $labasededatos;
$user = $elnombredelusuario;
$pass = $lacontasena;
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
答案 1 :(得分:1)
使用global
关键字使变量在函数内可用。 E.g:
public function DbConnector(){
global $elnombredelhost;
$host = $elnombredelhost;
// ... rest of your code
}
或者,您可以在连接文件中声明连接参数是常量并使用连接脚本中的常量:
在conexiongeneral.php
define('DB_HOST', 'your_db_host');
在您的连接类
中public function DbConnector(){
$host = DB_HOST;
// ... rest of your code
}