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特定功能。
请注意,为了安全起见,不要在代码中硬编码数据库的用户名和密码。最好是从配置文件或环境变量中读取这些信息。同时,确保你的代码能够妥善处理数据库连接失败的情况。
热点内容