我做了第一个连接到mysql数据库的函数。我有索引.php和函数.php我包括函数.php索引.php! 这是我的连接数据库功能...
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;
}
我不知道它是否正确,如果我称之为正确。
我输入索引.php
<?php
require_once 'functions.php';
connect_to_database();
active_links();
include 'includes/head.php';
include 'includes/nav.php';
..................。
查看评论:
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();
所以它现在工作正常,这是答案!谢谢你的帮助
我创建了名为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"));
}
只需像这样调用连接函数,$pdo = 连接(); 或 var 的任何名称,但这就是方式!
<?php
include 'config.php';
$pdo = connect();
........