Mysqli php common class

冷暖自知 提交于 2019-12-25 06:46:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!