我是PHP新手。
class metacountry
{
public $mysqli;
function metacountry()
{
global $config;
$mysqli=new mysqli($config['DBHostName'],$config['DBUserName'],$config['DBPassword'],$config['DBName']);
$mysqli->set_charset("utf8");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
function InsertCountry()
{
$stmt=$mysqli->prepare("insert into tbl_metacountry values(?,?,?,?,?)");
$stmt->bind_param('sssss', $country, $meta_title, $meta_keywords, $meta_description, $active);
$country=addslashes(addcslashes($mysqli->real_escape_string($_POST['country'], "%_")));
$meta_title=addslashes(addcslashes($mysqli->real_escape_string($_POST['meta_title'], "%_")));
$meta_keywords=addslashes(addcslashes($mysqli->real_escape_string($_POST['meta_keywords'], "%_")));
$meta_description=addslashes(addcslashes($mysqli->real_escape_string($_POST['meta_description'], "%_")));
$meta_active=addslashes(addcslashes($mysqli->real_escape_string($_POST['active'], "%_")));
$stmt->execute();
$stmt->close();
}
}
它会抛出错误:
致命错误:在/var/www/html/country.php中调用null上的成员函数prepare()
答案 0 :(得分:3)
您必须使用$this
来引用类属性。
你的联系:
$mysqli=new mysqli($config['DBHostName'],$config['DBUserName'],$config['DBPassword'],$config['DBName']);
应该是,
$this->mysqli[...]
其他信息
您应该在类中定义数据库设置,而不是使用global
,以使其更多 OO。
阅读材料
答案 1 :(得分:1)
我希望以下内容有意义 - 它没有经过测试,但看起来或多或少是正确的。数据库连接是在公共构造函数中创建的,并且为了清楚起见使用$this->conn
引用 - 尽管您当然可以将其重命名为您想要的任何内容。
<?php
class metacountry{
private $conn;
private $config;
public function __construct($config=array()){
/* initialise actual values at runtime */
$this->config=(object)array_merge(array(
'DBHostName' => false,
'DBUserName' => false,
'DBPassword' => false,
'DBName' => false
),$config);
$this->conn=new mysqli( $this->config->DBHostName, $this->config->DBUserName, $this->config->DBPassword, $this->config->DBName );
$this->conn->set_charset("utf8");
if( $this->conn->connect_errno ) {
printf( "Connect failed: %s\n", $this->conn->connect_error );
exit();
}
}
function InsertCountry(){
$stmt=$this->conn->prepare("insert into `tbl_metacountry` values (?,?,?,?,?)");
$stmt->bind_param('sssss', $country, $meta_title, $meta_keywords, $meta_description, $active );
$country=addslashes( addcslashes( $this->conn->real_escape_string( $_POST['country'], "%_" ) ) );
$meta_title=addslashes( addcslashes( $this->conn->real_escape_string( $_POST['meta_title'], "%_" ) ) );
$meta_keywords=addslashes( addcslashes( $this->conn->real_escape_string( $_POST['meta_keywords'], "%_" ) ) );
$meta_description=addslashes( addcslashes( $this->conn->real_escape_string( $_POST['meta_description'], "%_" ) ) );
$meta_active=addslashes( addcslashes( $this->conn->real_escape_string( $_POST['active'], "%_" ) ) );
$stmt->execute();
$stmt->close();
}
}
/* example */
$config=array(
'DBHostName'=>'localhost',
'DBUserName'=>'root',
'DBPassword'=>'password',
'DBName' =>'mydb'
);
$meta=new metacountry( $config );
if( $_SERVER['REQUEST_METHOD']=='POST' ) $meta->InsertCountry();
$meta=null;
?>