我有以下两个班:
1类:connection_class.php
class connection{
public $connection;
function __construct(){
$this->db_connect();
}
private function db_connect(){
$this->conn = @ new mysqli('localhost', 'username', 'password');
if ($this->connection->connect_error) {
$this->connection = FALSE;
$this->warn = '<br />Failed to connect database! Please try again later';
}
}
}
以及一个loginclass:
2类:login_class.php
class login{
private $conn;
function __construct($con){
if($con->connection==FALSE){
echo $con->warn;
exit();
}else{
$this->conn=$con->connection;
}
}
public function get_user($sql){
$this->db_select('database_name');
$result = $this->conn->query($logopt['sql']);
if($result->num_rows>=1){
return $result;
}else{
return FALSE;
}
}
}
现在从登录页面:
页码:login.php
include_once('connection_class.php');
$con = new connection();
include_once('login_class.php');
$login = new login($con);
$sql= "SELECT * FROM access WHERE username='".real_escape_string($user_name)."' AND password='".$pass_word."'";
$user=$login->getuser($sql);
if($user){
echo 'User found';
}else{
echo 'User not found';
}
如果我使用real_escape_string($user_name)或mysqli_real_escape_string($user_name),login.php将显示以下错误:
致命错误:调用中未定义的函数real_escape_string()
...........
在我的案例中,如何使用real_escape_字符串?
最佳答案
由于要将mysqli连接包装到另一个类中,因此需要公开一个方法来在连接类中调用real_escape_string
。
如:
class connection{
public $connection;
function __construct(){
$this->db_connect();
}
private function db_connect(){
$this->conn = @ new mysqli('localhost', 'username', 'password');
if ($this->connection->connect_error) {
$this->connection = FALSE;
$this->warn = '<br />Failed to connect database! Please try again later';
}
}
public function real_escape_string($string) {
// todo: make sure your connection is active etc.
return $this->conn->real_escape_string($string);
}
}
然后,改变
$sql= "SELECT * FROM access WHERE username='".real_escape_string($user_name)."' AND password='".$pass_word."'";
到
$sql= "SELECT * FROM access WHERE username='".$con->real_escape_string($user_name)."' AND password='".$pass_word."'";
附加注释:您的
login
类实际上没有使用您的连接来运行查询。你需要解决这个问题(特别是:$this->db_select('database_name');
)。