php根据请求参数ODBC动态连接SQL Server2008R2

使用场景:

  1.要使用php连接SQL Server2008R2

  2.要根据传入的参数来动态的切换数据库

<?php
    
    //查询sql Server所有的数据库名
    //SELECT Name FROM Master..SysDatabases 
    //master
    $strcaid = null;
    if(isset($_GET['strcaid'])){
        $strcaid = $_GET['strcaid'];
    }else if(isset($_POST['strcaid'])){
        $strcaid = $_POST['strcaid'];
    }else{
        echo "请在请求中加入strcaid";
        exit(0);
    }
    if(!preg_match("/[0-9]{4}/", $strcaid)){
        echo "请输入格式正确的strcaid";
        exit(0);
    }
    $dsn = "Driver={SQL Server};Server=(local);Database=";
    $dbName = "master";
    $conn = odbc_connect($dsn.$dbName, "sa", "123456") or die("Connection failed!");
    $sql = "SELECT Name FROM Master..SysDatabases";
    $ServerDBNames = odbc_do($conn, $sql);
    $dbName = null;
    //遍历所有数据库名
    while (odbc_fetch_row($ServerDBNames)){
        $Name=odbc_result($ServerDBNames,"Name");
        //把strcaid在每一个数据库名中查找
           if(strpos($Name, $strcaid) > 0){
               $dbName = $Name;
           }
    }
    
    //判断strcaid是否输入正确 
    if($dbName === null){
        echo "没有找到这个数据库,请查看id是否输入正确!!";
        exit(0);
    }
    $conn = odbc_connect($dsn.$dbName, "sa", "123456") or die("Connection failed!");
?> 

 

posted @ 2019-04-08 14:25  makalo  阅读(613)  评论(0编辑  收藏  举报