简体   繁体   中英

How to connect php webservice to sql server 2008 r2

We are developing php webservice and our database is on sql server 2008 r2

/* sql connection string */

     $link = mssql_connect('localhost','usrname','pass') or die('Cannot connect to the DB');     
     mssql_select_db('Data Source=PC-NAME;Initial Catalog=DBNAME.MDF;Persist Security Info=True',$link) or die('Cannot select the DB');

        /* grab the posts from the db */

        echo $query = "SELECT * FROM add_product WHERE prod_pos = '".$_GET['prod_pos']."'";
        $result = mssql_query($query,$link) or die('Errant query:  '.$query);

it gives fatal error on mssql_connect.

Fatal error: Call to undefined function mssql_connect() in service.php on line 11

So how to connect php webservice with sql server 2008 r2???

Thanks in advance...

You will need to download and install the sqlsrv extension from Microsoft. Look here for one option: http://www.microsoft.com/en-us/download/details.aspx?id=20098

Note that the extension is no longer called "mssql" but is instead now "sqlsrv" so you'll want to use sqlsrv_connect() , etc.

Got the Answer..............

    <?php
        $number_of_posts = $_GET['prod_pos']; 

        $format = 'json';

        /* connect to the db */

        $serverName = "(local)";

        /* Get UID and PWD from application-specific files.  */
        $uid = "usrname of sql server 2008";
        $pwd = "password";
        $connectionInfo = array( "UID"=>$uid, "PWD"=>$pwd, "Database"=>"db name" );

        /* Connect using SQL Server Authentication. */
        $conn = sqlsrv_connect( $serverName, $connectionInfo);
        if( $conn === false )
        {
             echo "Unable to connect.</br>";
             die( print_r( sqlsrv_errors(), true));
        }


        /* Query SQL Server for the login of the user accessing the database. */

        $tsql = "SELECT * FROM add_product WHERE prod_pos='".$number_of_posts."'";
        $stmt = sqlsrv_query( $conn, $tsql);
        if( $stmt === false )
        {
             echo "Error in executing query.</br>";
             die( print_r( sqlsrv_errors(), true));
        }


        /* create one master array of the records */

        $posts = array();
        while($post = sqlsrv_fetch_array($stmt) ) 
        {
                $posts[] = array('post'=>$post);
        }


        /* output in necessary format */

         if($format == 'json') 
         {
            header('Content-type: application/json');
            echo json_encode(array('posts'=>$posts));
         }

        /* disconnect from the db */

        $stmt = null; 
        $conn = null; 

     ?>

Successfully connected to the sql server 2008 r2 database using php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM