问题
I've recently started working with mysqli.
Previously with php and MySQL I would write a common class holding the MySQL database connection as I don't want to repeat that code over and over.
Now with mysqli I can't seem to do this.
Is there a simple way to do this I think I'm missing something really obvious.
回答1:
Have you considered using PDO?
Example:
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 );
来源:https://stackoverflow.com/questions/8314324/mysqli-php-common-class