導航:首頁 > 編程語言 > php新建資料庫連接

php新建資料庫連接

發布時間:2022-11-28 02:56:19

A. php網站怎麼連接到資料庫

常規方式

常規方式就是按部就班的讀取文件了。其餘的話和上述方案一致。

// 讀取配置文件內容
$handle = fopen("filepath", "r"); $content = fread($handle, filesize("filepath"));123

PHP解析XML

上述兩種讀取文件,其實都是為了PHP解析XML來做准備的。關於PHP解析XML的方式的博客有很多。方式也有很多,像simplexml,XMLReader,DOM啦等等。但是對於比較小型的xml配置文件,simplexml就足夠了。

配置文件

<?xml version="1.0" encoding="UTF-8" ?><mysql>
<!-- 為防止出現意外,請按照此標准順序書寫.其實也無所謂了 -->
<host>localhost</host>
<user>root</user>
<password>123456</password>
<db>test</db>
<port>3306</port></mysql>12345678910

解析

<?php/**
* 作為解析XML配置文件必備工具
*/class XMLUtil {
public static $dbconfigpath = "./db.config.xml"; public static function getDBConfiguration() {
$dbconfig = array (); try { // 讀取配置文件內容
$handle = fopen(self::$dbconfigpath, "r"); $content = fread($handle, filesize(self::$dbconfigpath)); // 獲取xml文檔根節點,進而獲取相關的資料庫信息
$mysql = simplexml_load_string($content); // 將獲取到的xml節點信息賦值給關聯數組,方便接下來的方法調用
$dbconfig['host'] = $mysql->host; $dbconfig['user'] = $mysql->user; $dbconfig['password'] = $mysql->password; $dbconfig['db'] = $mysql->db; $dbconfig['port'] = $mysql->port; // 將配置信息以關聯數組的形式返回
return $dbconfig;
} catch ( Exception $e ) { throw new RuntimeException ( "<mark>讀取資料庫配置文件信息出錯!</mark><br />" );
} return $dbconfig;
}
}

資料庫連接池

對於PHP程序而言,優化永無止境。而資料庫連接池就在一定程度上起到了優化的作用。其使得對用戶的每一個請求而言,無需每次都像資料庫申請鏈接資源。而是通過已存在的資料庫連接池中的鏈接來返回,從時間上,效率上,都是一個大大的提升。

於是,這里簡單的模擬了一下資料庫連接池的實現。核心在於維護一個「池」。

從池子中取,用畢,歸還給池子。

<?php/**x
* PHP中的資料庫 工具類設計
* 郭璞
* 2016年12月23日
*
**/class DbHelper { private $dbconfig; private $dbpool; public $poolsize; public function __construct($poolsize = 20) { if (! file_exists ( "./utils.php" )) { throw new RuntimeException ( "<mark>utils.php文件丟失,無法進行配置文件的初始化操作!</mark><br />" );
}else {
require './utils.php';
} // 初始化 配置文件信息
$this->dbconfig = XMLUtil::getDBConfiguration (); // 准備好資料庫連接池「偽隊列」
$this->poolsize = $poolsize;
$this->dbpool = array (); for($index = 1; $index <= $this->poolsize; $index ++) {
$conn = mysqli_connect ( $this->dbconfig ['host'], $this->dbconfig ['user'], $this->dbconfig ['password'], $this->dbconfig ['db'] ) or die ( "<mark>連接資料庫失敗!</mark><br />" );
array_push ( $this->dbpool, $conn );
}
} /**
* 從資料庫連接池中獲取一個資料庫鏈接資源
*
* @throws ErrorException
* @return mixed
*/
public function getConn() { if (count ( $this->dbpool ) <= 0) { throw new ErrorException ( "<mark>資料庫連接池中已無鏈接資源,請稍後重試!</mark>" );
} else { return array_pop ( $this->dbpool );
}
} /**
* 將用完的資料庫鏈接資源放回到資料庫連接池
*
* @param unknown $conn
* @throws ErrorException
*/
public function release($conn) { if (count ( $this->dbpool ) >= $this->poolsize) { throw new ErrorException ( "<mark>資料庫連接池已滿</mark><br />" );
} else {
array_push ( $this->dbpool, $conn );
}
}
}

B. PHp如何連接資料庫

PHP鏈接資料庫有幾種方式

mysqli:

<?php
$servername="localhost";
$username="username";
$password="password";
//創建連接
$conn=newmysqli($servername,$username,$password);
//檢測連接
if($conn->connect_error){

die("連接失敗:".$conn->connect_error);
}
echo"連接成功";
?>

也可以使用PDO進行鏈接,前提是你必須在php.ini中開啟PDO:

<?php
$servername="localhost";
$username="username";
$password="password";

try{
$conn=newPDO("mysql:host=$servername;dbname=myDB",$username,$password);
echo"連接成功";
}
catch(PDOException$e)
{
echo$e->getMessage();
}
?>

建議使用PDO,功能更加強大,兼容各種資料庫

C. 怎麼將php與資料庫連接

php鏈接mysql必備條件:
已安裝mysql資料庫;

檢查php環境是否已開啟mysql擴展(一般情況下是開啟的);
檢查方法:a.使用phpinfo();函數,看有沒有mysql項;b.打開php.ini文件,檢查php_mysql.dll前分號是否已取掉。
php鏈接代碼如下:
<?php
//設置編碼格式
header("Content-type:text/html;charset=utf-8");

//定義資料庫主機地址
$host="localhost";

//定義mysql資料庫登錄用戶名
$user="root";

//定義mysql資料庫登錄密碼
$pwd="";

//鏈接資料庫
$conn = mysql_connect($host,$user,$pwd);

//對連接進行判斷
if(!$conn){
die("資料庫連接失敗!".mysql_errno());
}else{

echo "資料庫連接成功!";
}
?>

D. php怎麼連接mysql資料庫

1、新建一個php_mysql.php的文件


E. 如何用php創建mysql資料庫

使用EclipsePHP Studio 3 創建一個PHP工程名稱為test1,在工程名下面userinfo的文件夾,然後在文件夾創建一個PHP文件(userinfo_create.php):

2
打開我們創建PHP文件:
先設置 地址,賬號,密碼:

$url = "127.0.0.1";//連接資料庫的地址
$user = "root"; //賬號
$password = "root";//密碼

//獲取連接$con = mysql_connect($url,$user,$password);

if(!$con){

die("連接失敗".mysql_error());

}

3
設置具體連接的數據,那我們這兒連接test資料庫,我們通過Navicat 打開mysql 資料庫
mysql_select_db("test");

F. PHP與資料庫的連接

PHP與資料庫連接最常用的方法有四種,它們分別是MySQL、mysqli、pdo、adodb,其中以第一種方法最常用,方法如下:
//與資料庫伺服器連接
$conn = @mysql_connect('資料庫主機名','用戶名','密碼');
//選擇具體資料庫
mysql_select('資料庫名',$conn);
//如果只打開了一個資料庫連接,則$conn可以省略。

G. 如何實現PHP自動創建資料庫

你做好程序以後,把資料庫導出成sql文件
1、連接資料庫
2、讀取這個sql文件里的sql語句,並執行
3、生成一個資料庫連接參數的php文件
<?php
$con=mysql_connect("localhost","peter","abc123");
if(!$con)
{
die('Couldnotconnect:'.mysql_error());
}

if(mysql_query("CREATEDATABASEmy_db",$con))
{
echo"Databasecreated";
}
else
{
echo"Errorcreatingdatabase:".mysql_error();
}

mysql_close($con);
?>

<?php
classReadSql{
//資料庫連接
protected$connect=null;
//資料庫對象
protected$db=null;
//sql文件
public$sqlFile="";
//sql語句集
public$sqlArr=array();
publicfunction__construct($host,$user,$pw,$db_name){
$host=empty($host)?C("DB_HOST"):$host;
$user=empty($user)?C("DB_USER"):$user;
$pw=empty($pw)?C("DB_PWD"):$pw;
$db_name=empty($db_name)?C("DB_NAME"):$db_name;
//連接資料庫
$this->connect=mysql_connect($host,$user,$pw)ordie("Couldnotconnect:".mysql_error());
$this->db=mysql_select_db($db_name,$this->connect)ordie("Yoncannotselectthetable:".mysql_error());
}
//導入sql文件
publicfunctionImport($url){
$this->sqlFile=file_get_contents($url);
if(!$this->sqlFile){
exit("打開文件錯誤");
}else{
$this->GetSqlArr();
if($this->Runsql()){
returntrue;
}
}
}
//獲取sql語句數組
publicfunctionGetSqlArr(){
//去除注釋
$str=$this->sqlFile;
$str=preg_replace('/--.*/i','',$str);
$str=preg_replace('//*.**/(;)?/i','',$str);
//去除空格創建數組
$str=explode("; ",$str);
foreach($stras$v){
$v=trim($v);
if(empty($v)){
continue;
}else{
$this->sqlArr[]=$v;
}
}
}
//執行sql文件
publicfunctionRunSql(){
foreach($this->sqlArras$k=>$v){
if(!mysql_query($v)){
exit("sql語句錯誤:第".$k."行".mysql_error());
}
}
returntrue;
}
}
//範例:
header("Content-type:text/html;charset=utf-8");
$sql=newReadSql("localhost","root","","log_db");
$rst=$sql->Import("./log_db.sql");
if($rst){
echo"Success!";
}
?>

H. php怎麼連接資料庫

1、資料庫連接第一步:配置mysql_connect()的參數
參數依次為:主機地址,用戶名,用戶密碼
2、mysql_pconnect()與mysql_connect()是不一樣的,pconnect顧名思義是持久連接
3、伺服器連接成功後,需要你選擇你需要用的資料庫
4、使用mydql_close()可以關閉資料庫連接資源,避免長時間佔用啟用資源消耗
5、mysqli_connect( )是mysql連接的另一種方式,參數形式一樣
6、首次使用mysql連接資料庫時,要記得使用輸入邏輯判斷,伺服器連接不成功或者選擇資料庫不成功,都要用Mysql_error或者mysql_errno來報錯
7、mysql的報錯,能夠幫助你准確地定位到錯誤發生在哪裡。

I. PHP7連接mysql資料庫方法

1、用 mysql_connect 的方法,PHP7會報致命錯誤

$conn= mysql_connect('localhost','xueyanxiang','xueyanxiang');

Fatal error : Uncaught Error: Call to undefined function mysql_connect() in /Users/xueyanxiang/work/test/xue.php:31 Stack trace: #0 /Users/xueyanxiang/work/test/xue.php(119): xue->run() #1 {main} thrown in  /Users/xueyanxiang/work/test/xue.php  on line  31

原因是:

PHP5中使用mysql_connect()函數進行連接,但實際上,PHP5.5開始,MySQL就不推薦使用了,屬於廢棄函數

PHP7中貌似已經徹底不支持了,根據官網說明,取而代之的是如下兩個:

本擴展自 PHP 5.5.0 起已廢棄,並在將來會被移除。應使用 MySQLi 或 PDO_MySQL 擴展來替換之。參見 MySQL:選擇

API 指南以及相關 FAQ 以獲取更多信息。用以替代本函數的有:

mysqli_connect()

PDO::__construct()

使用時,不要在使用mysql_connect了,可以換用mysqli_connect(),用法基本類似吧,據說是面向對象的庫。

php.ini中,也只有extension=php_mysqli.dll,而不再有extension=php_mysql.dll這個拓展了。

2、可以使用mysqli,對象化,方法名與被廢棄的類似

$conn= mysqli_connect('localhost','xueyanxiang','xueyanxiang');

3、PDO工具,推薦使用

$dbh= "mysql:host=localhost;dbname=test";

$db= new PDO($dbh,'xueyanxiang','xueyanxiang');

$objQuery= $db->query("select * from user;");

$res= $objQuery->fetchAll(PDO::FETCH_ASSOC);

不填寫參數的話,默認是關聯和索引都有,如下圖

J. PHPNOW中如何建立MYSQL資料庫連接

PHP和MySQL被稱為黃金搭檔,幾乎所有的基於PHP應用的項目都在使用MySQL,在PHP中,連接MySQL資料庫十分簡單,簡單到只需要一個函數函數即可:
mysql_connect($host,$username,$password)
它有三個參數,分別是資料庫主機名,資料庫用戶名,資料庫用戶密碼。

如果我們的資料庫在本地,那麼資料庫主機名可寫為127.0.0.1。例如,我們可以使用這個方法連接資料庫:
$con=mysql_connect('127.0.0.1','user','123456') or die("伺服器連接失敗!");
mysql_select_db('test',$con);
mysql_query("set names 'gb2312'");
三行代碼就實現了連接MySQL資料庫。在上面例子中,mysql_select_db()表示選擇資料庫,上例表示連接test資料庫,其中set names 'gb2312'表示設置資料庫讀取的編碼為gb2312。
如果資料庫的用戶名和密碼錯誤,頁面上自動會提示「伺服器連接失敗」。

一般的,我們在做OOP的開發當中,習慣上把PHP連接資料庫的部分,寫在一個單獨的類中。例如:
class cls_mysql
{
protected $link_id;
public function __construct($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8')//構造函數
{
if(!($this->link_id = mysql_connect($dbhost, $dbuser, $dbpw)))
{
$this->ErrorMsg("Can't pConnect MySQL Server($dbhost)!");
}
mysql_query("SET NAMES " . $charset, $this->link_id);//設置編碼
if ($dbname)
{
if (mysql_select_db($dbname, $this->link_id) === false )
{
$this->ErrorMsg("Can't select MySQL database($dbname)!");
return false;
}
else
{
return true;
}
}
}
public function select_database($dbname)//選擇資料庫
{
return mysql_select_db($dbname, $this->link_id);
}
public function fetch_array($query, $result_type = MYSQL_ASSOC)//得到遍歷後的數據,是一個數組形式
{
return mysql_fetch_array($query, $result_type);
}
public function query($sql)//執行查詢
{
return mysql_query($sql, $this->link_id);
}
public function affected_rows()//得到影響的記錄集數
{
return mysql_affected_rows($this->link_id);
}
public function num_rows($query)//獲得查詢的記錄數
{
return mysql_num_rows($query);
}
public function insert_id()
{
return mysql_insert_id($this->link_id);//獲得插入的id
}
public function selectLimit($sql, $num, $start = 0)
{
if ($start == 0)
{
$sql .= ' LIMIT ' . $num;
}
else
{
$sql .= ' LIMIT ' . $start . ', ' . $num;
}
return $this->query($sql);
}
public function getOne($sql, $limited = false)//獲取一條記錄
{
if ($limited == true)
{
$sql = trim($sql . ' LIMIT 1');
}
$res = $this->query($sql);
if ($res !== false)
{
$row = mysql_fetch_row($res);
return $row[0];
}
else
{
return false;
}
}
public function getrow($sql)
{
$res = $this->query($sql);
if ($res !== false)
{
return mysql_fetch_assoc($res);
}
else
{
return false;
}
}
public function getAll($sql)
{
$res = $this->query($sql);
if ($res !== false)
{
$arr = array();
while ($row = mysql_fetch_assoc($res))
{
$arr[] = $row;
}
return $arr;
}
else
{
return false;
}
}
function ErrorMsg($message = '', $sql = '')
{
if ($message)
{
echo "<b>error info</b>: $message\n\n";
}
else
{
echo "<b>MySQL server error report:";
print_r($this->error_message);
}
exit;
}
}

閱讀全文

與php新建資料庫連接相關的資料

熱點內容
單片機頻率變化 瀏覽:428
哪個app可以看賭神 瀏覽:466
rstudiopython 瀏覽:127
團隊如何開發伺服器 瀏覽:440
php選擇資料庫的函數 瀏覽:772
dhcp伺服器新增地址 瀏覽:930
程序員跑三個月外賣 瀏覽:941
linux配置tomcat的jdk路徑 瀏覽:363
液體壓縮公式 瀏覽:777
php開發後台管理系統 瀏覽:360
python二分查找遞歸 瀏覽:447
微信如何發視頻不壓縮 瀏覽:902
河北2021美術高考綜合分演算法 瀏覽:606
如何為電腦文件夾加密 瀏覽:835
電腦自啟動應用命令 瀏覽:690
php判斷一個文件是否存在 瀏覽:829
php導出xml文件 瀏覽:904
7個文件夾解壓 瀏覽:383
python實現機器碼 瀏覽:356
jpeg壓縮器 瀏覽:98