我对以下代码有疑问。这是一个 PHP 类,我计划将其用作 DB-Handler。对于 INSERT,我使用了一个小辅助函数,主要是因为我懒得手动清理字符串。这是代码:
<?php
class Db{
/*
* Configure DB settings here, make sure php is in good health. Check phpinfo();
*/
private $MYSQL_HOST = 'localhost';
private $MYSQL_USER = 'root';
private $MYSQL_PASS = '******';
private $db;
function select($selected_db, $sql){
//Create new object out of connection to db
$this->db = @new mysqli($this->MYSQL_HOST, $this->MYSQL_USER, $this->MYSQL_PASS, $selected_db);
//If there aren't any errors
if(mysqli_connect_errno() == 0){
$result = $this->db->query($sql);
if($result){
$result = $result->fetch_array(MYSQLI_ASSOC);
}else{
echo "There is a problem with the query";
}
} else { //If you couldn't connect to DB at all
die("No connection possible: " . mysqli_connect_error());
}
//Close connection
$this->db->close();
return $result;
}
function dirtyLittleHelper($string){
//Change each character into its HTML equivalent
$string = htmlentities($string);
//Create a legal SQL string from input
$string = $this->db->mysqli_real_escape_string($string);
return $string;
}
}
?>
现在对于我得到的错误:
致命错误:在第 35 行的 /path/to/file/db_class.php 中的非对象上调用成员函数 mysqli_real_escape_string()
问题只是为什么?我不想使用未经处理的字符串,也不想使用 mysql_real_escape_string 因为它已被弃用。
因为这是我第一次使用 SQL,所以我冒着风险发布一个问题的副本。对我来说,正确学习它很重要,而不仅仅是使用有效的版本,让数据库的方式保持开放。
在此先感谢 Stiller_leser
编辑
谢谢,我想我会用难以捉摸的暗示去。我不知道,它准备这样做。无论如何只是为了检查,正确的插入功能可能看起来像那样吗?
function insert($selected_db, $sql){
//Create new object out of connection to db
$this->db = @new mysqli($this->MYSQL_HOST, $this->MYSQL_USER, $this->MYSQL_PASS, $selected_db);
//If there aren't any errors
if(mysqli_connect_errno() == 0){
//If you could prepare query
if($result = $db->prepare( $sql )){
//Execute query
$result->execute();
} else { //If you couldn't prepare query
echo "There is a problem with the query";
}
} else { //If you couldn't connect to DB at all
die("No connection possible: " . mysqli_connect_error());
}
//Close connection
$this->db->close();