Each time you include this library, it will connect to the mysql database. You can use $db as the link identifier. I sometimes add all the project related database functions under db.php, it makes the code easier to maintenance.
Usage:
include_once( 'db.php' );
Include the file and use $db as the link identifier.Install:
- Copy db.php and config.ini.php.
- Set the connection parameters in config.ini.php
db.php:
<?php
// Can use $db for mysqli function after included this file
include_once( 'config.ini.php' );
$db = @mysqli_connect( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME )
or die( 'Could not connect to database: ' . mysqli_connect_error() );
mysqli_set_charset( $db, 'utf8' );
/*
* Database functions used in this specified project
*/
function foo() {
global $db;
$sql = sprintf( "SELECT * FROM user WHERE id='%s';", 1 );
$result = $db->query( $sql );
if ( $result->num_rows == 1 ) {
$row = $result->fetch_assoc();
// do something for exactly one record found.
}
while ( $row = $result->fetch_assoc() ) {
// do something for each record.
}
}
?>
config.ini.php:
<?php
define( 'DB_HOST', 'localhost' );
define( 'DB_USER', 'root' );
define( 'DB_PASSWORD', '' );
define( 'DB_NAME', 'test' );
?>
No comments:
Post a Comment