首页 > 编程技术 > php

php下导入.sql到数据库的方法

发布时间:2016-11-25 16:37

以前我们都是利用phpmyadmin或在dos下进行.sql文件的导入,今天我们来看看在php下同样可以实现把.sql文件导入到mysql数据库中哦。
 代码如下 复制代码
<?php
$conn=mysql_connect(“localhost”,”root”,”password”);//指定数据库连接参数function mysql_import($file,$database)// 导入的函数,参数为SQL文件路径和导入的库名。
{
mysql_select_db($database);
mysql_query(“source ‘”.$file.”‘;”);
echo “导入”.$file.”文件到”.$database.”数据库完毕”;
}
mysql_close($conn);
?>
本文章简单的利用了php的pdo来连接微软的mssql server数据库哦,下面来看看实例,有需要的朋友可以参考一下。
 代码如下 复制代码

$dsn = 'mssql:dbname=bookStore_demo;host=192.168.1.106';
$user = 'sa';
$password = '123';
    //mssql_connect('192.168.1.106','sa','123');
    //echo 22;
try {
       // echo 11;
    $dbh = new PDO($dsn, $user, $password);

} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
//$sql = 'select * from article';
$sth = $dbh->query($sql);
$result = $sth->fetchAll();

var_dump($result);

含三个页面,cogfig页面是被包含页面。denglu页面负责提交,session赋值等,denglu_link页面负责权限判断的演示。 本例事先已存在test数据库,user_list表,表中有uid,m_id,username,password四个字段。并且password字段已经经过md5加密,形式是:md5(\"用户密码\".ALL_PS),即用户输入的密码加常量进行加

先来看配置文件

 

 代码如下 复制代码
<?php教程
//启动session
session_start();
//数据库教程连接
$conn=mysql教程_connect('localhost','root','******');
mysql_select_db('test',$conn);
//定义常量
define("ALL_PS","php100");
//判断权限函数
function user_shell($uid,$shell){
$sql="SELECT * FROM `user_list` WHERE `uid` = '$uid'";
$query=mysql_query($sql);
$exist=is_array($row=mysql_fetch_array($query));
$exist2=$exist?$shell==md5($row['username'].$row['password'].ALL_PS):FALSE;
if($exist2){
return $row;
}else{
echo "你无权限访问该页";
exit();
}
}
?>


登录页面

 

 代码如下 复制代码
<?
include("config.php");
if($_POST['submit']){
$username=str_replace(" ","",$_POST['username']); //去除空格
$sql="SELECT * FROM `user_list` WHERE `username` = '$username'";
$query=mysql_query($sql);
$exist=is_array($row=mysql_fetch_array($query)); //判断是否存在这样一个用户
$exist2=$exist?md5($_POST['password'].ALL_PS)==$row['password']:FALSE;//判断密码
if($exist2){
$_SESSION['uid']=$row['uid']; // session赋值
$_SESSION['user_shell']=md5($row['username'].$row['password'].ALL_PS);
echo "登陆成功";
}else{
echo "不正确的用户名";
SESSION_DESTROY();
}
}
?>
<form action="" method="post">
用户名:<input type="text" name="username" /><br>
密码:<input type="password" name="password"/><br>
验证码:<input type="code" name="code" size="10"/>
<img" width=100% src="imgcode.php"><br><br>
<input type="submit" name="submit" value="登陆"/>
</form>
<a href="http://127.0.0.1/test/denglu_link.php">denglu_link</a>

权限判断页面

 

 代码如下 复制代码
<?
include("config.php");
$arr=user_shell($_SESSION['uid'],$_SESSION['user_shell']);//以上两句即可对权限进行判断
echo $arr['username'];
?>

权限内容

面向对象的方式
先看看如果连接错误等的处理,PHP中PDO的错误处理,使用面向对象的方式来处理:

<?php教程
try {
 $db = new PDO('mysql教程:host=localhost;dbname=test', $user, $pass);
 $db = null;
} catch (PDOException $e) {
 print "Error: " . $e->getMessage() . "<br/>";
 die();
}
?>
这里利用我们PHP 5面向对象的异常处理特征,如果里面有异常的话就初始化调用PDOException来初始化一个异常类。
PDOException异常类的属性结构:

<?php
class PDOException extends Exception
{
 public $errorInfo = null; // 错误信息,可以调用 PDO::errorInfo() 或 PDOStatement::errorInfo()来访问
 protected $message; // 异常信息,可以试用 Exception::getMessage() 来访问
 protected $code; // SQL状态错误代码,可以使用 Exception::getCode() 来访问
}
?>
这个异常处理类是集成PHP 5内置的异常处理类,我们简单的看一下PHP 5内置的异常处理类结构:

<?php
class Exception
{
 // 属性
 protected $message = 'Unknown exception'; // 异常信息
 protected $code = 0; // 用户自定义异常代码
 protected $file; // 发生异常的文件名
 protected $line; // 发生异常的代码行号

 // 方法
 final function getMessage(); // 返回异常信息
 final function getCode(); // 返回异常代码
 final function getFile(); // 返回发生异常的文件名
 final function getLine(); // 返回发生异常的代码行号
 final function getTrace(); // backtrace() 数组
 final function getTraceAsString(); // 已格成化成字符串的 getTrace() 信息
}
?>
相应的,在代码中可以合适的调用 getFile() 和 getLine() 来进行错误定位,更方便的进行调试。

使用面向过程的方法
先看代码:

<?
$db = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$rs = $db->query("SELECT aa,bb,cc FROM foo");
if ($db->errorCode() != '00000'){
 print_r($db->errorInfo());
 exit;
}
$arr = $rs->fetchAll();
print_r($arr);
$db = null;
?>
PDO和PDOStatement对象有errorCode() 和 errorInfo() 方法,如果没有任何错误, errorCode() 返回的是: 00000 ,否则就会返回一些错误代码。errorInfo() 返回的一个数组,包括PHP定义的错误代码和MySQL的错误代码和错误信息,数组结构如下:

Array
(
 [0] => 42S22
 [1] => 1054
 [2] => Unknown column 'aaa' in 'field list'
)
每次执行查询以后,errorCode() 的结果都是最新的,所以我们可以很容易自己控制错误信息显示

为了让自己的数据类能够做到最大化的重用,就写个能够重用的PDO操作MySql的类:


由于pdo可以连接现在流行的各种数据库教程,所以单独的写个配置类类来完成不同数据库DSN的配置

<?php教程
/**
 * 类标准说明    PDO连接数据库的配置类
 * 类名:     ConfigDataBase
 * 功能说明:    为了让代码重用,利用此类可以动态的连接各种数据库
 * 参数说明:    $_dbms = "mysql教程";    //数据库类型
 *         $_host = '127.0.0.1';     //数据库ip地址
 *         $_port = '3306';     //数据库端口
 *         $_username = 'root';    //数据库用户名
 *        $_password = 'liujijun';   //密码
 *         $_dbname = 'zendf';        //数据库名 默认为zenf
 *         $_charset = 'utf-8';       //数据库字符编码
 *         $_dsn;//                    //data soruce name 数据源
 *
 *
 * 类属性说明:
 * 类方法说明:
 * 返回值:     不同函数返回不同的值
 * 备注说明:
 * 作者:       刘纪君
 * 最后一次修改时间:    2011下午02:01:39
 *
 */
class ConfigDataBase {
 
 protected static $_dbms = "mysql";    //数据库类型
    protected static $_host = '127.0.0.1';     //数据库ip地址
    protected static $_port = '3306';     //数据库端口
    protected static $_username = 'root';    //数据库用户名
    protected static $_password = 'liujijun';   //密码
    protected static $_dbname = 'zendf';        //数据库名 默认为zenf
    protected static $_charset = 'utf-8';       //数据库字符编码
    protected static $_dsn;//                    //data soruce name 数据源
 
 /**
  *@return   返回数据源名
  */
 public static function getDsn() {
  //将变量的值组合成  mysql:host=localhost;port =3306;dbname=test',$login,$passwd的形式
  if (!isset(self::$_dsn)){
    self::$_dsn = self::$_dbms.':host = '.self::$_host.';prot = '.
    self::$_port . ';dbname = ' . self::$_dbname.','.
    self::$_username . ','.self::$_password;
 
    if (strlen(self::$_charset) > 0){
     self::$_dsn = self::$_dsn . ';charset = ' . self::$_charset;
    }
  }
  return self::$_dsn;//返回数据源名
 }
 
 /**
  * 功能:设置$dbms
  * @param $dbms
  */
 public static function setDbms($dbms){
  if (isset($dbms) &&(strlen($dbms) > 0 )){
   self::$_dbms = trim($dbms);
  }
 }
 
 /**
  *
  * @param  $host  //数据库地址
  */
 public static function setHost($host){
  if (isset($host) &&(strlen($host) > 0 )){
   self::$_host = trim($host);
  }
 }

 /**
  *
  * @param $host 端口号
  */
 public static function setPort($port){
  if (isset($port) &&(strlen($port) > 0 )){
   self::$_post = trim($port);
  }
 }
 
 /**
  *
  * @param  $passwd 密码
  */
 public static function setPasswd($passwd){
  if (isset($passwd) &&(strlen($passwd) > 0 )){
   self::$_password = trim($passwd);
  }
 }
 
 /**
  *
  * @param  $username 用户名
  */
 public static function setUsernName($username){
   if (isset($username) &&(strlen($username) > 0 )){
    self::$_username = trim($username);
   }
  }
 
 /**
  *
  * @param  $dbname 数据库名
  */
 public static function setDbName($dbname){
   if (isset($dbname) &&(strlen($dbname) > 0 )){
    self::$_dbname = trim($dbname);
   }
  }
 
 
  /**
   *
   * @param  $charset 数据库编码
   */
 public static function setCharset($charset){
   if (isset($charset) &&(strlen($charset) > 0 )){
    self::$_charset = trim($charset);
   }
  }
}

下面是对数据库的操作:

 

<?php

require_once 'ConfigDataBase.php';
header("Content-Type: text/html; charset=utf-8");//设置编码
/**
 * 类标准说明
 * 类名:      PdoMysql
 * 功能说明:     对数据库进行各种操作
 * 参数说明:
 * 类属性说明:
 * 类方法说明:
 * 返回值:
 * 备注说明:
 * 作者:       刘纪君
 * 最后一次修改时间:    2011上午10:45:36
 *
 */
class  PdoMysqlOperater{
 
 
 /**
  * @return 返回连接数据库的句柄
  */
 public function getConnection(){
  $connection = NULL;
  try {
   $connection = new PDO(ConfigDataBase::getDsn());
   echo 'Success';
  } catch (PDOException  $e) {
   print "Error in connection :".$e->getMessage().' '.die();
  }
  return $connection;
 }
 
 /**
  *
  * @param  $connection    连接数据库的句柄
  */
 public function closeConnection($connection){
  try {
   if ($connection != null) {
    $connection = null;//关闭数据库连接句柄
   }
  } catch (Exception $e) {
   print 'Close the connectin is error:'.$e->getMessage();
  }
 
 }
 
 /**
  * 功能:      向数据库中增加数据
  * @param $sql      sql语句
  */
 public  function insertDatabase($sql){
  $affect = false;//失败返回false
  try {
   $conn = $this->getConnection();
   $conn->exec($sql);
   $affect = true;//插入成功返回true
   $this->closeConnection($conn);//关闭数据库
  } catch (PDOException $e) {
   print 'Insert error '.$e->getMessage();
  }
  return $affect;//返回值
 }
 
 /**
  *
  * @param $id      表的主键id
  * @param $tableName    表名
  */
 public function deleltById($id,$tableName){
  $affact = false;
  $sql = 'delete from '.trim($tableName).' where id = '.$id;
  try {
   $conn = $this->getConnection();
   $conn->exec($sql);
   $this->closeConnection($conn);
   $affact = true;
  } catch (PDOException  $e) {
   print 'Delelte error is '.$e->getMessage();
  }
  return $affact;
 }
 
 /**
  * 功能:      以and 的形式删除记录
  * @param $tableName    表的名称
  * @param $array        数组表中字段名=其值的方式进行组合
  */
 public  function prepareDeleteAnd($tableName,array $array=null){
  $sql = 'delete from '. $tableName . ' where ';
  $count = count($array);//计算数组的长度
  $flag = 0;//设置标记

  foreach ($array as $key => $value){
   $flag++;//让flag增加一
   $sql .= $key .'='."'".$value."'";
   if ($flag != $count ){//当falg不等于count时,数组还有值,后面增加and,反之不增加
    $sql .= ' and ';
   }
  }
  echo  $sql;//测试sql语句的组合 
  try {
   $conn = $this->getConnection();//获取连接
   $conn->prepare($sql);
   $this->closeConnection();
  } catch (PDOException $e) {
   print 'Delete error is '.$e->getMessage();
  }
 
 }
 

 /**
  * 功能:         以or 的形式删除记录
  * @param $tableName    表的名称
  * @param $array        数组表中字段名=其值的方式进行组合
  */
 public  function prepareDeleteOr($tableName,array $array=null){
 
  $sql = 'delete from '. $tableName . ' where ';
  $count = count($array);//计算数组的长度
  $flag = 0;//设置标记

  foreach ($array as $key => $value){
   $flag++;//让flag增加一
   $sql .= $key .'='."'".$value."'";
   if ($flag != $count ){//当falg不等于count时,数组还有值,后面增加and,反之不增加
    $sql .= ' or ';
   }
  }
  echo  $sql;//测试sql语句的组合 
  try {
   $conn = $this->getConnection();//获取连接
   $stmt = $conn->prepare($sql);
   $stmt->execute();//执行
   $this->closeConnection();
  } catch (PDOException $e) {
   print 'Delete error is '.$e->getMessage();
  }
 
 }
 
 
 /**
  * 功能:      取得表中所有数据
  * @param  $sql     sql语句
  */
 public function getAll($sql){
 
  $result = null;
  try {
   $conn = $this->getConnection();
   $result = $conn->query($sql);
   $this->closeConnection($conn);
  } catch (PDOException $e) {
   print 'GetAll error is '.$e->getMessage();
  }
 }
 
 
 /**
  * 功能:更新数据表中的信息
  * @param  $table      要更新的表名
  * @param array $updateFiled    要更新的字段
  * @param array $updateConditon 更新需要的条件
  */
 public function updateDataBase($table,array $updateFiled,array $updateConditon ){
  
  $sql   = 'update from ' .$table .' set ';
 
  //对set字段进行赋值操作
  $count = count($updateFiled);//获取要修改数组的长度
  $flag  = 0;//设置标记为0
  foreach ($updateFiled as $key => $value){
   $flag++;
   $sql .= $key .'='."'".$value."'";
   if ($flag != $count){
    $sql .=',';
   }
  }
  //对where条件进行赋值
  $countUpdateCondition = count($updateConditon);//获取要修改数组的长度
  $flag  = 0;//设置标记为0
  $sql .= ' where ';
  foreach ($updateConditon as $key => $value){
   $flag++;
   $sql .= $key .'='."'".$value."'";
   if ($flag != $countUpdateCondition){
    $sql .=' and ';
   }
  }
  try {
   $conn = $this->getConnection();
   $conn->exec($sql);
   $this->closeConnection($conn);
  } catch (PDOException $e) {
   print 'Update error is :'.$e->getMessage();
  }
 
 }
 
 
 /**
  * 功能:      根据表和提高的查询条件进行查询
  * 返回值:      返回结果集
  * @param  $table    数据表名
  * @param array $findCondition  查询条件
  */
 public function findData($table,array $findCondition){
 
  $sql = 'select from '.$table .' where ';
 
  $count = count($findCondition);//获取查询条件数组的长度
  $flag  = 0;//设置标记为0
  foreach ($findCondition as $key => $value){
   $flag++;
   $sql .= $key .'='."'".$value."'";
   if ($flag != $count){
    $sql .=' and ';
   }
  }
  try {
    $conn = $this->getConnection();
    $conn->exec($sql);
    $this->closeConnection($conn);
   } catch (PDOException $e) {
    print 'find error is :'.$e->getMessage();
   }
  
  }
}
//测试

$db = new PdoMysqlOperater();
$db->findData('liujijun',array('name'=>'liujijun','name1'=>'liujijun'));

标签:[!--infotagslink--]

您可能感兴趣的文章: