Data | database
<?php
Require_once (' db_config.php ') in another file for security reasons.
Class Dbmanager
{
private static $conn;
public static function getconnection ()
{
if (self:: $conn ===null)
{
$newConn = @new mysqli (hostname,username,password,dbname);
if (Mysqli_connect_errno ()!==0)
{
$msg =mysqli_connect_error ();
throw new Databaseerrorexception ($msg);
}
@ $newConn->query ("Set names \ utf8\ '");
Self:: $conn = $newConn;
}
Return self:: $conn;
}
};
?>
<?php
/*
This is a class for database management, and the primary role of this class is to do some extra work when connecting to a database, in which you can see whether the database is connected each time you connect to the database, thus saving resources by ensuring that there is always only one database connection. And the user doesn't have to think about whether or not the connection already exists, I can get a connection through $conn=dbmanager::getconnection () as long as the database connection is used and if there is a connection before it is uncertain. In addition, this class also does a job, query (' Set names ' \utf-8\ '), which tells the database this query and write using the Utf-8 character set, which is also necessary.
The following is a usage example:
Require_once ("db_manager.php");
$conn =dbmanager::getconnection ();
$result =@ $conn->query ("SELECT * from Stuinfo");
if (Mysqli_connect_errno ())
Echo Mysqli_connect_error ();
$rowNum = $result->num_rows;
echo "\ $rowNum = $rowNum";
echo ' <br/> ';
Called again, but the last connection was returned.
$conn =dbmanager::getconnection ();
Var_dump ($conn);
*/
?>