Mysqli php common class


Mysqli php common class

我最近开始使用mysqli。

以前使用php和MySQL时,我会编写一个公共类来保存MySQL数据库连接,因为我不想一遍又一遍地重复该代码。

现在我似乎不能这样做。

有没有简单的方法来做这件事我想我错过了一些很明显的东西。

您考虑过使用PDO吗?

的例子:

session_start();
$db_user = 'example';
$db_pass = 'xxxxx';
$user_id = 1;
try
{
    $db=new PDO( "mysql:host={$db_host}dbname={$db_name}", $db_user, $db_pass);
}
catch ( Exception $e )
{
    exit( "Error connecting to database: " . $e->getMessage() );
}
$statement = $db->prepare( "SELECT * FROM user WHERE user_id=:user_id" );
// http://www.php.net/manual/en/pdostatement.bindvalue.php
$statement->bindValue( ':user_id', $user_id, PDO:: PARAM_INT );
$statement->execute();
// http://www.php.net/manual/en/pdostatement.fetch.php
// fetches an object representing the db row.
// PDO::FETCH_ASSOC is another possibility
$userRow = $statement->fetch( PDO::FETCH_OBJ );
var_dump( $userRow );