note 69328 deleted from function.mssql-query by cmb
| From: | cmb@php.net | Date: | Sun, 23 Jun 2019 14:23:53 +0000 |
| Subject: | note 69328 deleted from function.mssql-query by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-211374@lists.php.net to get a copy of this message | ||
Note Submitter: cuzco
----
This one took me several days to figure out so I thought I'd post the solution to save others
the hassle.
When using mssql_query with freetds inside a php class, you *MUST* include the
"link_identifier" in the mssql_query() call otherwise all your queries will fail. This
differs from MySQL where omitting the link identifier works without problem.
Here's an example class to illustrate the problem/solution
<?php
class MSSQLDB
{
var $db_connection;
// Constructor
function __construct($inFreeTDSServerName, $inUser, $inPassword, $inDatabaseName)
{
$this->db_connection = mssql_connect($inFreeTDSServerName, $inUser,$inPassword)
or die('Could not connect to '.$inFreeTDSServerName.' server');
mssql_select_db($inDatabaseName)
or die('Could not select to '.$inDatabaseName.' database');
}
// Generic query function
function query_database($inQuery)
{
// Always include the link identifier (in this case $this->db_connection) in mssql_query
$query_result = mssql_query($query, $this->db_connection)
or die('Query failed: '.$query);
if (strpos($inQuery, 'insert') === false)
{
// fetch the results as an array
$result = array();
while ($row = mssql_fetch_object($query_result))
{
$result[] = $row;
}
// dispose of the query
mssql_free_result($query_result);
// return result
return $result;
}
else
{
// dispose of the query
mssql_free_result($query_result);
// get the last insert id
$query = 'select SCOPE_IDENTITY() AS last_insert_id';
$query_result = mssql_query($query)
or die('Query failed: '.$query);
$query_result = mssql_fetch_object($query_result);
mssql_free_result($query_result);
return $query_result->last_insert_id;
}
}
}
?>
And to use the class with the following freetds.conf record
[SomeDatabaseServer]
host = somedbserver.com
port = 1433
tds version = 8.0
<?php
$db = new MSSQLDB('SomeDatabaseServer', 'user', 'password',
'database');
$query = "select * from table";
return $db->query_database($query);
?>