PHP sqlsrv_query执行语法错误

时间:2013-01-29 04:39:25

标签: php sql-server sql-server-2008

我正在尝试通过PHP执行SQL查询,其中我将数据库配置存储在单独的文件中。

以下是PHP文件:

文件:db_config.php

<?php
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "MAVERICK"); // db server
?>

文件:db_connect.php

<?php

/** A class file to connect to database */

class DB_CONNECT
{
    // constructor
        function __construct() 
    {
            // connecting to database
            $this->connect();
        }

        // destructor
        function __destruct() 
    {
            // closing db connection
            $this->close();
        }

    /** Function to connect with database */
    function connect()
    {
            // import database connection variables
            require_once __DIR__ . '/db_config.php';

           // Connecting to SQL Server database
            $serverName = DB_SERVER; 
        $connectionInfo = array("Database"=>DB_DATABASE);       
        $conn = sqlsrv_connect($serverName, $connectionInfo) or die(sqlsrv_errors());  
        return $conn;
    }

    /** Function to close the database connection */
    function close()
    {
        sqlsrv_close();
    }
}
?>

文件:get_all_products.php

<?php 
/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = sqlsrv_query($db,"SELECT * FROM products");

if( $result ) {
     echo "Query executed.<br />";
}else{
     echo "Query could not executed.<br />";
     die( print_r( sqlsrv_errors(), true));
}

?>

不幸的是,它正在回归。数据库连接成功。我很难找到为什么sqlsrv_query无法正常工作。

Query could not executed.
Array ( [0] => Array ( [0] => IMSSP [SQLSTATE] => IMSSP [1] => -14 [code] => -14 [2] => An invalid parameter was passed to sqlsrv_query. [message] => An invalid parameter was passed to sqlsrv_query. ) )

对此的任何帮助都会非常有帮助。

谢谢!!!

1 个答案:

答案 0 :(得分:1)

将db连接对象分配给类成员。

function __construct() 
{
    // connecting to database
    $this->db_conn = $this->connect();
}

然后将其用作:

$result = sqlsrv_query($db->db_conn,"SELECT * FROM products");