php開發資料庫
發布時間: 2025-03-29 15:05:08
你做好程序以後,把資料庫導出成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!";
}
?>
⑵ php怎麼連接資料庫
在PHP中連接資料庫,一般使用PDO或者MySQLi擴展庫來實現。
使用PDO連接資料庫時,你需要先創建一個新的PDO實例,提供資料庫的連接信息,如DSN、用戶名和密碼。例如:$pdo = new PDO;。之後,你就可以使用這個$pdo對象來執行SQL查詢和其他資料庫操作了。
而使用MySQLi連接資料庫,你需要創建一個mysqli對象,並傳入資料庫的連接信息。例如:$mysqli = new mysqli;。連接成功後,你也可以通過這個$mysqli對象來進行資料庫操作。
這兩種方式都能有效地連接和操作資料庫,選擇哪一種主要取決於你的具體需求和編程習慣。不過,一般來說,PDO的跨資料庫兼容性更好,而MySQLi則提供了更多的MySQL特定功能。
請注意,為了安全起見,不要在代碼中硬編碼資料庫的用戶名和密碼。最好是從配置文件或環境變數中讀取這些信息。同時,確保你的代碼能夠妥善處理資料庫連接失敗的情況。
熱點內容