用于连接mysql数据库的函数

时间:2015-01-18 19:02:32

标签: php mysql function pdo

我创建了第一个连接mysql数据库的函数。我有index.php和functions.php,我把functions.php包含在index.php中!  这是我的Connect to database function ...

function connect_to_database()
{

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

try {
$dbh = new PDO("mysql:host=$hostname;dbname=zadatak1", $username, $password);
/*** echo a message saying we have connected ***/
/**echo 'Connected to database';**/
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $dhb;

}

我不知道这是否正确,如果我说的是对的。

我输入index.php

<?php

require_once 'functions.php';

connect_to_database();

active_links();

include 'includes/head.php';

include 'includes/nav.php'; 

..................

2 个答案:

答案 0 :(得分:0)

见评论:

function connect_to_database()
{

   /*** mysql hostname ***/
   $hostname = 'localhost';

   /*** mysql username ***/
   $username = 'root';

   /*** mysql password ***/
   $password = '';

   $dbh = false; // initialized for error

   try {
      $dbh = new PDO("mysql:host=$hostname;dbname=zadatak1", 
                    $username, $password);
      /*** echo a message saying we have connected ***/
      /**echo 'Connected to database';**/
   }
   catch(PDOException $e)
   {
       echo $e->getMessage();
       // consider to exit / throw own exception / stop continuing script anyhow ....
   }

   // returns false on error
   return $dbh; // typo here, was $dhb !!  
}

用法:

$DB = connect_to_database(); 

if ( $DB !== false )
    $DB->function();

答案 1 :(得分:0)

现在它工作正常,这是答案!谢谢你的帮助

我创建了名为config.php的文件

// PDO connect *********
function connect() 
{
    $host = 'localhost';
    $db_name = 'database_name';
    $db_user = 'root';
    $db_password = '';
    return new PDO('mysql:host='.$host.';dbname='.$db_name, $db_user, $db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}

只是像这样调用connect函数,$ pdo = connect();或者var的任何名称,但这就是方法!

<?php

include 'config.php';

$pdo = connect();

........