我有两个课程如下:
class-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: class-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_string?
答案 0 :(得分:3)
由于您将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');
)。
答案 1 :(得分:0)
您忘记在函数开头添加msql_
正确的函数mysql_real_escape_string();
如上所述使用此代替real_escape_string();
。
希望这能解决您的问题。