PHP Write a small class of database management (to be upgraded)

Source: Internet
Author: User
Tags character set php write
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);


*/
?>



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.