我正在尝试连接到我的数据库,但无法连接。我尝试过但无法连接。我得到的错误是解析错误:语法错误,第 3 行 C:\htdocs\www\dating\index.php 中出现意外的“连接”(T_STRING)。我调用了尝试过的 new Database connect();并尝试连接();我收到此消息 Fatal error: Call to undefined function connect() in C:\htdocs\www\dating\index.php on line 3。出了什么问题?
class Database{
private $db_host = "localhost";
private $db_user = "123346";
private $db_pass = "12345";
private $db_name = "1234";
public $conn;
// Create connection
public function connect(){
if(!isset($this->conn)){
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);
if($this->conn){
$this->conn = true;
return true;
}else{
$this->conn = false;
return false;
}
}
}
public function disconnect(){
if(isset($this->conn)){
if(mysqli_close($this->conn)){
$this->myconn = false;
echo "connection closed";
return true;
} else{
echo "failed to close connection";
return false;
}
}else{
echo "no connection prescent";
}
}
}
我现在尝试获取 use 查询,但它不会得到结果。这是代码
include("functions/connect.php");
$db = new Database("localhost", "12345", "1234", "123");
$db->connectdb();
$db->select('rpg');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT id, username FROM users ORDER by ID DESC ";
if ($result = $db->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
/* free result set */
$result->close();
}
/* close connection */
$db->close();`
最佳答案
请更改此行
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);
到此
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
您会注意到您使用了$this->pass
,但它应该是$this->db_pass
。
要调用Database类的函数,你必须这样编写代码;
<?php
include("functions/connect.php");
$db_conn = new Database();
if($db_conn->connect()) {
echo "Database connected";
}
关于php - 我的类(class)无法连接到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42826905/