I am getting "Fatal error: Invalid handle returned. in" in PHP 7 while trying to connect with SQL Server.
I have already tried below option
Error connecting to MSSQL with SQLSrv and PHP 5.4.7
Unable to connect to SQL Server with PHP
I am using below code:
try {
$conn = new PDO( "sqlsrv:Server=(10.10.10.222\sql2008r2);Database=test",'sa', 'sipl#123');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
echo "Connected to SQL Server\n";
$query = 'SELECT *FROM atlas_positions';
$stmt = $conn->query( $query );
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
echo '<pre>';
print_r( $row );
echo '</pre>';
}
Your views will be beneficial for me.
Try "ConnectionPooling=0" in DSN, it worked for me.
$conn = new PDO( "sqlsrv:Server=(10.10.10.222\sql2008r2);Database=test;ConnectionPooling=0",'sa', 'sipl#123');
(My answer is based on #maydimanche's answer from here)
Related
I am trying to connect to an existing SQL Server database using PDO with the drivers provided by Microsoft.
I have seen examples using odbc, dblib, mssql, etc., however I believe the connection string with these drivers should use 'sqlsrv'?
Are there any good examples of how to properly do this? If I should be doing this via some other method please let me know. Thanks!
Well that's the best part about PDOs is that it's pretty easy to access any database. Provided you have installed those drivers, you should be able to just do:
$db = new PDO("sqlsrv:Server=YouAddress;Database=YourDatabase", "Username", "Password");
Mind you that in my experience and also of other (PHP - Why is new SQLSRV driver slower than the old mssql driver?) that using PDO_SQLSRV is way slower than through PDO_ODBC.
If you want to use the faster PDO_ODBC you can use:
//use any of these or check exact MSSQL ODBC drivername in "ODBC Data Source Administrator"
$mssqldriver = '{SQL Server}';
$mssqldriver = '{SQL Server Native Client 11.0}';
$mssqldriver = '{ODBC Driver 11 for SQL Server}';
$hostname='127.0.0.1';
$dbname='test';
$username='user';
$password='pw';
$dbDB = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=$dbname", $username, $password);
This works for me, and in this case was a remote connection:
Note: The port was IMPORTANT for me
$dsn = "sqlsrv:Server=server.dyndns.biz,1433;Database=DBNAME";
$conn = new PDO($dsn, "root", "P4sw0rd");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM Table";
foreach ($conn->query($sql) as $row) {
print_r($row);
}
Figured this out. Pretty simple:
new PDO("sqlsrv:server=[sqlservername];Database=[sqlserverdbname]", "[username]", "[password]");
try
{
$conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
$servername = "";
$username = "";
$password = "";
$database = "";
$port = "1433";
try {
$conn = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
echo ("Error connecting to SQL Server: " . $e->getMessage());
}
Good morning,
i'm trying to make a responsive web page, though the combined use of Html5, css3 and php 7.2 (configured with microsoft SqlServer-2008-R2, because the company has the database stored there yet).
Now, i'm trying to make it modular, so i want to have:
Home.php (with the html structure of the page),
Styles.css (with the style of the page),
Classes.php (with all the declarations of classes and functions that Home.php can call and use while needed, like OpenConnection etc...).
The problem is that i can't call the functions from the classes.php file.
I'm trying to open the connection to our server but it doesn't work.
this is my actual code for the Classes.php file:
<?php
class Connessioni {
function apriConn ($srv, $db){
/* Get UID and PWD from application-specific files. */
$uid = file_get_contents("C:\inetpub\wwwroot\MoviDex\Parametri\UidPwd\uid.txt");
$pwd = file_get_contents("C:\inetpub\wwwroot\MoviDex\Parametri\UidPwd\pwd.txt");
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>$db);
try {
$conn = new PDO( "sqlsrv:server=".$srv.";Database = ".$db, $uid, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
echo "Connected to SQL Server\n";
return $conn;
}
?>
and this is how i call it from the Home.php:
<table class="w3-table-all w3-hoverable w3-card-4 ">
<?php
require (classes.php);
$serverName = "xxx.xxx.x.x";
$database = "EDP";
$conn= apriConn($serverName, $database);
$query = "My query, that it does work, i've used it yet directly in sql server";
$stmt = $conn->query( $query );
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
print_r( $row );
}
// Free statement and connection resources.
$stmt = null;
$conn = null;
?>
</table>
Can you please help me ?
thank you so much.
I am trying to connect to an existing SQL Server database using PDO with the drivers provided by Microsoft.
I have seen examples using odbc, dblib, mssql, etc., however I believe the connection string with these drivers should use 'sqlsrv'?
Are there any good examples of how to properly do this? If I should be doing this via some other method please let me know. Thanks!
Well that's the best part about PDOs is that it's pretty easy to access any database. Provided you have installed those drivers, you should be able to just do:
$db = new PDO("sqlsrv:Server=YouAddress;Database=YourDatabase", "Username", "Password");
Mind you that in my experience and also of other (PHP - Why is new SQLSRV driver slower than the old mssql driver?) that using PDO_SQLSRV is way slower than through PDO_ODBC.
If you want to use the faster PDO_ODBC you can use:
//use any of these or check exact MSSQL ODBC drivername in "ODBC Data Source Administrator"
$mssqldriver = '{SQL Server}';
$mssqldriver = '{SQL Server Native Client 11.0}';
$mssqldriver = '{ODBC Driver 11 for SQL Server}';
$hostname='127.0.0.1';
$dbname='test';
$username='user';
$password='pw';
$dbDB = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=$dbname", $username, $password);
This works for me, and in this case was a remote connection:
Note: The port was IMPORTANT for me
$dsn = "sqlsrv:Server=server.dyndns.biz,1433;Database=DBNAME";
$conn = new PDO($dsn, "root", "P4sw0rd");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM Table";
foreach ($conn->query($sql) as $row) {
print_r($row);
}
Figured this out. Pretty simple:
new PDO("sqlsrv:server=[sqlservername];Database=[sqlserverdbname]", "[username]", "[password]");
try
{
$conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
$servername = "";
$username = "";
$password = "";
$database = "";
$port = "1433";
try {
$conn = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
echo ("Error connecting to SQL Server: " . $e->getMessage());
}
Trying to see if I can make PDO open my mssql database on my server. With vbscript my call to the connection looks like this:
set MyConn = Server.CreateObject("ADODB.Connection")
MyConn.Open("dsn=MYDSN;uid=MYUID;pwd=MYPWD;DATABASE=MYDATABASE;APP=ASP Script")
Then when trying to port this over to php using PDO I was unable to find any information on using DSN with PDO.
Here is what I have so far:
try {
$conn = new PDO('mssql:Server=localhost;Database=MYDSN','MYUID','MYPWD') or die('error');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT name FROM people";
$qresult = $conn->prepare($sql);
$qresult->execute();
foreach ($qresult->fetch(PDO::FETCH_ASSOC) as $row){
echo $row['name'].'<br/>';
}
} catch (PDOException $e) {
print "Error!: ".$e->getMessage()."<br/>";
die();
}
But this is what I get
Error!: SQLSTATE[HY000]: General error: 10007 Invalid object name 'name'. [10007] (severity 5) [(null)]
My guess is because I cannot put the dsn anywhere in the pdo code.
First of all: I did a research on google and stackoverflow, but it does not helped me.
I'm a beginner, so please do not blame me directly by just reading the title and voting me down. Stackoverflow seems to be very aggressive sometimes :(
I'm trying to execute a simple stored procedure from PHP.
Connecting to the database works.
This code also works through a query in SQL Server Management Studio:
Execute SP_TPL_DeleteUser
#ExternalFieldID = 22
Regarding to this manuals: PHP Stored Procedures and SQL Server and MSSQL Bind
I build this lines of code:
$id=22;
$stmt=mssql_init("SP_TPL_DeleteUser", $conn);
mssql_bind($stmt, "#ExternalFieldID", $ExternalFieldID, SQLVARCHAR, false, false, 255);
mssql_execute($stmt);
mssql_free_statement($stmt);
My output is:
( ! ) Fatal error: Call to undefined function mssql_init() in
C:\Users\kians_000\dev\traka\index.php on line 32
Of course I tried playing around, but nothing works :(
I would be thankful for any tips.
Edit:
I can connect to the DB with this:
$serverName = "KIAN-PC";
$connectionInfo = array( "Database"=>"T32Database");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.\n";
}
else
{
echo "Connection could not be established.\n";
die( print_r( sqlsrv_errors(), true));
}
But a simple query like this:
$version = mssql_query('SELECT * FROM [T32Database].[dbo].[TUsers]');
$row = mssql_fetch_array($version);
echo $row[0];
Produces this output:
Fatal error: Call to undefined function mssql_query() in C:\Users\kians_000\dev\traka\index.php on line 42
phpinfo show me this:
sqlsrv
sqlsrv support enabled
Directive Local Value Master Value
sqlsrv.ClientBufferMaxKBSize 10240 10240 sqlsrv.LogSeverity 0 0
sqlsrv.LogSubsystems 0 0 sqlsrv.WarningsReturnAsErrors On On
Edit 3:
I tried out all drivers. This is the only one that works.
Maybe something with my source is wrong.
<?php
//-----------------------------------------------
// Connect to SQL Server DB
//-----------------------------------------------
$serverName = "KIAN-PC";
$connectionInfo = array( "Database"=>"T32Database");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.\n";
}
else
{
echo "Connection could not be established.\n";
die( print_r( sqlsrv_errors(), true));
}
//-----------------------------------------------
// Perform operations with connection.
//-----------------------------------------------
$version = mssql_query('SELECT * FROM [T32Database].[dbo].[TUsers]');
$row = mssql_fetch_array($version);
echo $row[0];
/* Close the connection. */
sqlsrv_close( $conn);
?>
My output is:
Connection established. ( ! ) Fatal error: Call to undefined function
mssql_query() in C:\Users\kians_000\dev\traka\index.php on line 42
Instead of binding try calling your procedure as a query:
mssql_query('exec SP_TPL_DeleteUser #ExternalFieldID = ' . $ExternalFieldID, $con);
I mixed together two different drivers.
There are mssql and sqlsrv drivers.
Check if the statements begin with mssql_ or sqlsrv_
I use MSSQL Express 2012 and it seems like the mssql drivers aren't used anyway.
This here works now (as a hello world):
<?php
//-----------------------------------------------
// Connect to MSSQL-DB
//-----------------------------------------------
$serverName = "KIAN-PC";
$connectionInfo = array( "Database"=>"T32Database");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
//-----------------------------------------------
// Perform operations with connection.
//-----------------------------------------------
if( $client_info = sqlsrv_client_info( $conn)) {
foreach( $client_info as $key => $value) {
echo $key.": ".$value."<br />";
}
} else {
echo "Error in retrieving client info.<br />";
}
/* Close the connection. */
sqlsrv_close( $conn);
?>
Thanks for everybodys help anyway!
If you're using WAMP, make sure that the mssql module is enabled. It will have a checkmark next to its name in the context menu if it is.