PHP function using PDO for databse

function db_connect()
{
    $dsn = "mysql:host=localhost;dbname=test;charset=utf8";
    $opt = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    return new PDO($dsn,'root','', $opt);
}
 
 
$pdo = db_connect();

but note again - unlike with mysql_query(), you have to always use this $pdo variable for your queries.
 
you need not a boolean but PDO object. 
 
 
  • PDO is OO, meaning the connection to the database is represented by a PDO Object.
  • Your db_connect() function should return the object that gets created.
  • Passing in the parameters required by PDO will give you more flexibility!