我在PHP下面的代碼連接到我的數據庫:PHP - 呼叫到空的成員函數查詢() - 錯誤
<?php
class MY_SQL{
private $username;
private $password;
private $conn;
public function __construct($SERVERNAME){
$this->username = "username";
$this->password = "password";
if($SERVERNAME == "data_"){
$server = "Servername";
}
else {
$server = $SERVERNAME;
}
// Create connection
$conn = new mysqli($server, $this->username, $this->password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
public function SQLCommand($cmd) {
if ($this->conn->query($cmd) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $cmd . "<br>" . $conn->error;
}
}
}
$sql = "INSERT INTO _test(test1, test2) VALUES ('hello','hi');";
$database = new MY_SQL("Servername");
$database->SQLCommand($sql);
?>
我收到以下錯誤:
Fatal error: Call to a member function query() on null
出了什麼問題?
忘記選擇數據庫提高你的類! – Saty
@Saty你是對的! – float