PHP Connection to SQL Server DB - php

I am having connection issues when trying to connect from a PHP script to a SQL server database.
I have used the PDO method - My script can be seen below, connecting using Windows authentication, the object referenced in my script has been created in the database, roles and permissions have been defined.
I am testing locally using WAMP, calling a simple file called insert.php from the webroot.
My SQL server is installed on the same machine and my SQL version is 2012.
The script when executed should simply echo the results of the PATIENT table to the screen for now.
In both of my Apache and PHP versions of the php.ini file i have added the necessary extension to use the sqlsrv drivers and installed all the of the necessary drivers.
Yet still I get the error:
could not find driver1
The script:
<?php
try
{
$conn = new PDO("sqlsrv:Server=localhost ;Database=MindTrackDb", "", "");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(Exception $e)
{
die( print_r( $e->getMessage() ));
}
$tsql = "SELECT * FROM PATIENT";
$getResults = $conn->prepare( $tsql);
$getResults->execute();
$results - $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row) {
echo $row['PATIENT_ID'].''.$row['FORENAMES'].''.$row['SURNAME'].''.$row['EMAIL'];
echo '<br>';
}
?>
My question is 2 part really:
A) Is this the best method to communicate to a SQL server database with PHP or is there a better method?
B) What could the driver error possibly be - I have followed various suggestions from here and nothing has worked.

Related

How to connect to sql database through php/pdo that has been exported from mysql/phpmyadmin as mydatabase.sql?

I have searched on many different sites and cannot find an answer that specifically answers this question:
I have WAMP Server installed, which installed phpmyadmin as well as MySQL. I can easily connect to the database through php/pdo by using localhost as my hostname.
But my problem is I am trying to connect to a database that I have exported from phpmyadmin as "mydatabase.sql". So now lets say I placed this file on my pc at "C:\Users\Username\Desktop\MyFolder\mydatabase.sql". How would I connect to this database (if this is possible)?
The reason is that I cannot install WAMP Server on all the pcs that would use this program. so would like to be able to connect to the database without having to install any type of servers, etc...
My php at the moment is:
<?php
$dsn='mysql:C:\Users\Username\Desktop\MyFolder\mydatabase.sql';
$username='username';
$password='pass';
try
{
$dbh = new PDO("$dsn",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to Database<br/>';
$sql = "SELECT * FROM users";
foreach ($dbh->query($sql) as $row)
{
echo $row["ID"] ." - ". $row["Name"] ."<br/>";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Also, if this is possible, would username and password be necessary to connect to an "off server database"?
If I try:
$dsn='sqlite:C:\Users\Optique\Desktop\optique.sql';
I get:
"Connected to Database
SQLSTATE[HY000]: General error: 26 file is encrypted or is not a database"
But I think that is because SQLite uses a different database format than MySQL (stand to be corrected). So what I need is something similar to the SQLite driver for MySQL.
Thanks in advance!
You cannot find an answer simply because it doesn't exist: it's impossible to connect to an SQL dump through PDO, and it makes no sense anyway: a dump is not a database but simply a collection of INSERT queries. Unlike sqlite, for mysql you need a server to connect with.
To be able to connect, you should import that dump into mysql database first and then connect to that database with PDO.

ERROR: could not find driver - Using PDO with MS Access database

Background:
I've got a fully working Microsoft Access DB. I've made a database connection class and just a simple page that includes the class and fires off a simple SQL code. I know the code is right as it was working fine a few weeks ago. However, in between then and now I installed PHP, MySQL, set up my IIS and installed PHPMyAdmin. (We were having problems with our servers so tried going localhost but it was resolved before I fully used PHPMyAdmin).
So now I've got my connection class and simple php page onto the server (using FTP). However, when I run the same query I used a few weeks ago i'm now getting the error message:
ERROR:could not find driver. Warning: file_put_contents(connection.errors.txt) [function.file-put-contents]: failed to open stream: Permission denied in E:\kunden\blah\blah\blah\www\simpleTest.php on line 31
The Code
connectionClass.php:
class connection{
public $con;
private $dbName;
function __construct(){
$this->dbName = $_SERVER["DOCUMENT_ROOT"] . "../database/db.mdb";
}
function connect(){
$this->con = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$this->dbName; Uid=Admin; Pwd=;");
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $this->con;
}
}
simpleTest.php
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}
try{
include_once 'classes/connectionClass.php';
//get the DB connection
$con = new connection();
$pdoConnection = $con->connect();
//query the DB
$sql = $pdoConnection->prepare("SELECT * FROM celebs");
$result = $sql->execute();
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo $row['firstname'];
echo $row['surname'];
}
} catch (Exception $e){
echo 'ERROR:'.$e->getMessage();
file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
}
I've not changed the code and was wondering if setting up PHP, MySQL, IIS and PHPMyAdmin has done something to prevent me from my code working? I've looked in phpinfo(); but i'm not really sure what to be looking for.
Any help is MUCH appreciated, thank you.
EDIT: In addition, after some de-bugging - i'm fairly certain the error revolves around the code in simpleTest.php after trying to make a new connection...
Manipulating an Access database from PHP via ODBC has some serious limitations that affect both PDO and the older odbc_exec methods. If you are using a Windows server and you absolutely must use an Access database back-end (which is strongly discouraged) I would recommend that you use ADO under com_dotnet like this:
<?php
// this code requires the following php.ini directive:
//
// extension=php_com_dotnet.dll
$con = new COM("ADODB.Connection");
$con->Open(
"Provider=Microsoft.Jet.OLEDB.4.0;" .
"Data Source=C:\\Users\\Public\\mdbTest.mdb");
$rst = new COM("ADODB.Recordset");
$rst->Open("SELECT * FROM celebs", $con, 1, 3); // adOpenKeyset, adLockOptimistic
while (!$rst->EOF) {
echo $rst["firstname"]->Value . " " . $rst["surname"]->Value . "<br/>";
$rst->MoveNext;
}
$rst->Close();
$con->Close();
This is especially true if you ever need full Unicode character support or expect to be manipulating binary objects.

Trying to connect with sql server database

I'm trying to connect sql server with php, i'm trying to get info from the database..
Now, here is what i got:
try {
$user = '';
$pass = '';
$objDb = new PDO('mysql:host=192.168.10.250;dbname=WEB_POROSIA',
'$user', '$pass');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM 'WEB_POROSIA'
";
$statement = $objDb->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo $e->getMessage();
}
I receive this error:
SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
This is my first attempt to connect php with sql server, and i don't know what this output means, i mean i don't know what might cause it!
I'm using xampp.
Thanks
It appears that you are trying to connect using the wrong driver.
For Sql Server you might want to use PDO ODBC driver not the mysql method you are trying to use.
You need to use a different DBO driver.
Check out other ODBC drivers, i.e PDO.
The code you have written tries to connect to a MySQL database rather than a MSSQL one.
You'll want to do something like this:
$db_connection = new PDO("dblib:dbname=$db_name;host=$host", $username, $password);
You can find more information here: http://grover.open2space.com/content/use-php-and-pdo-connect-ms-sql-server

How to connect to MSSQL in PHP using sqlsrv api?

I am trying to connect to MSSQL in PHP using sqlsrv api. When I run phpinfo(), it shows an a section for sqlsrv. But while actually writing code, I cannot connect to MSSQL. I am using SQL Server R2. I connect to the database from the Management Studio using the specified hostname. Here is the code:
<?php
$serverName = "TEST-PC\SQLEXPRESS";
$databaseName = "TestDB";
$connectionInfo = array("Database"=>"$databaseName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ){
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
else{
echo "Connection created";
}
$tsql = "SELECT * FROM Test";
$result = sqlsrv_query($conn, $tsql);
echo "Rows returned: ".sqlsrv_num_rows($result);
sqlsrv_close();
?>
The code prints NOTHING on the page, not even any error message. Here is the entries in php.ini file:
extension=php_sqlsrv_53_ts_vc9.dll
extension=php_pdo_sqlsrv_53_ts_vc9.dll
Any help please?
Since you did not pass a user or password, the driver is trying to connect via Windows Authentication. By running PHP from IIS, it will connect with the credentials of what whatever user IIS is running under (such as NT AUTHORITY\IUSR). You need to add the IIS user to the list of allowed logins to SQL Server, and then add a user associated with that login to the database.
Did you mean to put "$connectionOptions" where you have "$connectionOptions"?
Turn on error_reporting for php for more verbose output.
[EDIT]
A few possibile solutions:
Check your Connection String properties for the MSSQL Database you're connecting to (i.e. are you matching the values exactly, or can you use (local)
It's possible the User you're logged in on doesn't have proper access to the database. That sounds like an oversimplification, but check out your IIS settings, as well as FastCGI.impersonate settings. Turn on IIS Windows Authentication settings in IIS, and fastcgi.impersonate = 1. There's a thorough article about this potential issue here: http://blogs.msdn.com/b/brian_swan/archive/2010/02/10/sql-server-driver-for-php-understanding-windows-authentication.aspx
It is because sqlsrv_query() uses SQLSRV_CURSOR_FORWARD cursor type by default. However, in order to get a result from sqlsrv_num_rows(), you should choose one of these cursor types below:
SQLSRV_CURSOR_STATIC
SQLSRV_CURSOR_KEYSET
SQLSRV_CURSOR_CLIENT_BUFFERED
For more information, check: Cursor Types (SQLSRV Driver)
In conclusion, Try this Code:
$tsql=sqlsrv_query("SELECT * FROM Test");
$row_count = sqlsrv_num_rows($tsql);
echo $row_count;

Call to undefined function query() - using PDO in PHP

I have a written a script in PHP that reads from data from a MySQL database. I am new to PHP and I have been using the PDO library. I have been developing on a Windows machine using the WAMP Server 2 and all has been working well. However, when I uploaded my script to the LINUX server where it will be used I get the following error when I run my script.
Fatal error: Call to undefined function query()
This is the line where the error is occuring ...
foreach($dbconn->query($sql) as $row)
The variable $dbconn is first defined in my dblogin.php include file which I am listing below.
<?php
// Login info for the database
$db_hostname = 'localhost';
$db_database = 'MY_DATABASE_NAME';
$db_username = 'MY_DATABASE_USER';
$db_password = 'MY_DATABASE_PASSWORD';
$dsn = 'mysql:host=' . $db_hostname . ';dbname=' . $db_database . ';';
try
{
$dbconn = new PDO($dsn, $db_username, $db_password);
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Error connecting to database: ' . $e->getMessage();
}
?>
Inside the function where the error occurs I have the database connection defined as a superglobal as such ...
global $dbconn;
I am a bit confused as to what is happening since all worked well on my development machine. I was wondering if the PDO library was installed but from what I thought it was installed by default as part of PHP v5.
The script is running on an Ubuntu (5.0.51a-3ubuntu5.4) machine and the PHP version is 5.2.4. Thank you for any suggestions. I am really lost on this.
Always, but always, develop on the same platform as your production platform. Try your best to mirror the versions of server software (PHP, MySQL, etc). There will always be differences between installs, and especially in the way different OS platforms handle things. Use the old 'phpinfo()' script on each server to compare the differences, if any.
At any rate, even if both the Win and Linux platforms here have the exact same versions of everything, have you checked your configuration? In other words, is the MySQL host name in your DSN a local MySQL host (linked to your Win development platform), or the actual host the Ubuntu server uses? Or are they both "localhost" in either case? Double check this. Also, have you mirrored all data on both servers?
Do you know for a fact that the Ubuntu server has PDO? You essentially said you assume they are the same. Don't assume, verify.
As sobedai mentioned, look at the output of var_dump($dbconn), check that it is actually a PDO object, and go from there.
This is a typical PDO deployment for me:
// 'logger' is a custom error logging function with email alerts
try {
$dbh= new PDO(dsn);
if ( is_a($dbh, "PDO") ) {
$sql= 'SELECT field FROM table';
$stmt= $dbh->query($sql);
if ( is_a($stmt, "PDOStatement") ) {
// handle resultset
}
else {
// weirdness, log it
logger("Error with statement: {$sql}" .$dbh->errorCode());
}
}
else {
// some weirdness, log it
logger('Error making connection: '. $dbh->errorCode());
}
}
catch (PDOException $e) {
logger('PDOException caught in '.__FILE__.' : '. $e->getMessage());
}
catch (Exception $e) {
logger('General Exception caught in '.__FILE__.' : '. $e->getMessage());
}
Note I'm using PDO::errorCode in there, referencing the SQL-92 state codes.
Also, refer to the manual as much as possible.
Generally when this happens, the object you're trying to reference is not actually an instance of a class.
Since you've been developing on WAMP and testing on LAMP, include paths immediately come to mind.
Check the php includes path is correct on your LAMP stack.
Check that all the necessary libs are installed (just do a quick phpinfo() page or you can use php -i from the command line).
And last but not least - do:
echo var_dump($dbconn);
confirm that it is indeed the object you think it is.

Categories