我有一个连接类,应该为我连接到数据库,但它不起作用。
连接.php-
<?php
require_once "config.php";
class connection{
public static $db_con;
public function __construct(){
$this->db_con = new mysqli($server_name, $user_name, $password, $database_name);
if($this->db_con->connect_error){
echo "Connection falied for " . $this->db_con->connect_errno . "\n";
return $this->db_con->connect_errno;
}
else{
echo "Connection Successful";
return $this->db_con;
}
}
}
?>
我的 config.php 看起来像 -
<?php
define("server_name", "localhost:8889");
define("database_name", "myStore");
define("user_name", "root");
define("password", "root");
?>
在我的索引页中,我尝试通过执行以下操作来建立数据库连接
<?php
require_once "connection.php";
$db = new connection();
?>
我应该看到成功消息或错误消息,但我什么也没得到。总空白页。任何人都可以帮忙吗?
我正在根据 u_mulder 的建议更新文件,这解决了一个问题,但现在又出现了另一个问题。
现在我正在吃以下错误-
注意: undefined variable :connection.php 第 10 行中的 server_name undefined variable :connection.php 第 10 行中的 user_name
最佳答案
通过__construct
函数定义类构造函数。
在旧的php版本中,构造函数也可以命名为类名,即connection
目前,您的函数__connection
只是一个函数,而不是构造函数。要么将其重命名为构造函数,要么显式调用它:
$db = new connection();
$db->__connection();
此外,变量 $server_name、$user_name、$password、$database_name
在 connection
类的范围内不可用。您应该将它们作为参数传递给函数,或者将值声明为常量。
更新:
如果您将某些值定义为常量,正如您所说:
define("server_name", "localhost:8080");
那么server_name
是一个常量名称,并且应该使用不带$
符号:
$this->db_con = new mysqli(server_name, user_name, password, database_name);
为了不将常量与变量混合,建议使用 UPPER_CASE
命名常量,例如:
define("SERVER_NAME", "localhost:8080");
关于php - mysqli 连接不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34120484/