我现在来自.Net背景学习php。我想设置一种方法来在函数中使用我的数据库连接字符串,以便我可以调用它。我创建了一个类,只是想看看这是否正确完成或者我是否犯了任何错误。这是我的代码:
页面:module.php
// Database Connection Settings
$_SESSION['servername'] = "localhost";
$_SESSION['mysql_username'] = "user12345";
$_SESSION['mysql_password'] = "mypass12345";
$_SESSION['dbname'] = "dbnamehere";
class db_Class{
function db_conn() {
//global $conn;
$conn = new mysqli($_SESSION['servername'], $_SESSION['mysql_username'], $_SESSION['mysql_password'], $_SESSION['dbname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
}
页面:test.php
//Bring the class into the page for access.
include_once("module.php");
//Access our class.
$db_Class = new db_Class;
$conn = ($db_Class->db_conn());
//connect to the database.
$sql = "SELECT id, region FROM tbl_region;";
$result = $conn->query($sql);
//Print the results out.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<td align="left" valign="top"><p>'.$row["region"].'</p></td></tr>';
}
}
这是为PHP和数据库连接设置面向对象编程的正确方法吗?如果没有,请你解释我做错了什么?
答案 0 :(得分:1)
database.php中
<?php
class Database {
const HOST = 'localhost';
const USERNAME = 'root';
const PASSWORD = 'root';
const DATABASE = 'test';
private static $instance;
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new mysqli(Database::HOST, Database::USERNAME, Database::PASSWORD, Database::DATABASE);
if (mysqli_connect_error()) {
throw new Exception('Unable to connect to mysql server ' . mysqli_connect_error());
}
}
return self::$instance;
}
}
test.php的
//Bring the class into the page for access.
include_once("Database.php");
// Database Connection
$conn = Database::getInstance();
//connect to the database.
$sql = "SELECT id, region FROM tbl_region;";
$result = $conn->query($sql);
//Print the results out.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<td align="left" valign="top"><p>'.$row["region"].'</p></td></tr>';
}
}