search
Homephp教程php手册php写的数据库管理的小类(待升级)

数据|数据库

require_once('db_config.php');//为了安全考虑放在另一个文件中.

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;
 }
};

?>
/*
这是数据库管理的类,定义这个类的主要作用是做连接数据库时的一些额外工作,在这个类中,每次连接数据库时都查看一下数据库是否已经连接,这样就能保证永远只有一个数据库连接,从而节省了资源。而使用者也不用考虑以前是否已经存在这个连接,只要用到数据库连接,而且在不确定之前是否有连接的情况下,我都可以通过$conn=DBManager::getConnection()获得一个连接。另外,这个类还做了一个工作,query('set names '\utf-8\'),这样告诉数据库本次查询和写入使用utf-8字符集,这也是很有必要的。
如下为一个使用范例:


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 '
';

//再次调用,但返回的还是上一次的连接.
$conn=DBManager::getConnection();
var_dump($conn);


*/
?>



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.