I am trying to execute SQL query via PHP, where I database configuration stored in a separate file.
Below are the PHP file :
File : db_config.php
<?php
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "MAVERICK"); // db server
?>
File : 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();
}
}
?>
File : 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));
}
?>
Unfortunately , it is returning. The database connection is successful. I am struggling to find why sqlsrv_query is not working.
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. ) )
Any help on this would be very helpful.
Thanks !!!
Assign the db connection object to a class member.
function __construct()
{
// connecting to database
$this->db_conn = $this->connect();
}
Then use it as:
$result = sqlsrv_query($db->db_conn,"SELECT * FROM products");
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.