我目前正在开展一个小项目,为了上帝的爱,我无法让这个PHP课程运作。
问题是,doQuery
在我输入和INSERT或任何其他命令时,不会返回任何内容或修改数据库,即使从类中调用也总是返回false。
class CONN {
private $connection;
public function __construct() {
$this->connection = new mysqli($address, $user, $pass, $db);
if ($this->connection->connect_error) {
// Throw error here
} else {
$this->doQuery("SET NAMES 'utf8'");
}
}
public function doQuery($query){
return $this->connection->query($this->connection->real_escape_string($query));
}
}
解决
real_escape_string甚至转义为'
,因此查询无效。
答案 0 :(得分:2)
我认为你的代码不会像那样工作,我看到的主要问题是以下代码:
$this->connection = new mysqli($address, $user, $pass, $db);
$ adress,$ user,$ pass,$ db来自哪里?也许你错过了构造函数的论点。
答案 1 :(得分:1)
仅将real_escape_string
用于转义变量(通常由用户提交),例如
$this->doQuery("SELECT * FROM table WHERE something='".$this->connection->real_escape_string($_POST['data'])."'"
不要转义整个查询
public function doQuery($query){
return $this->connection->query($query);
}
答案 2 :(得分:0)
您需要创建/提供其他类参数。创建对象时,类构造函数需要这些值来建立连接。所以:
class Con
{
private $address;
private $username;
private $password;
private $database;
public function __construct($address, $username, $password,$database)
{
$this->address = $address;
$this->username = $username;
$this->password = $password;
$this->database = $database;
}
public function connect()
{
$con = mysqli_connect($this->address, $this->username, $this->password, $this->database);
return $con;
}
}
$conobject = new Con("localhost","root","","mybase");
$convar = $conobject->connect();