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

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.

Related

PHP Connection to SQL Server DB

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.

Cannot connect to MYSQL in MAMP using PHP

I just installed MAMP and have created a MYSQL database. I can access it via PHPMYADMIN.
In my php page I have this, pasted directly from the MAMP webstart page--
$user = 'root';
$password = 'root';
$db = 'local_db';
$host = 'localhost';
$port = 3306;
$link = mysql_connect(
"$host:$port",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
The resulting page stops at this point, won't print anything below these instructions.
I've tried changing the port in the MAMP preferences. I also included or die("Could not connect"); after the first line, but still don't get any text after the link data in the page.
I checked online, and others with the problem at least see the die text. I don't get that.
I haven't changed any passwords or data other than mess with the port number.
Any help would be appreciated!
Please give the following a try, I have developed and tested it locally, functionality within has been documented to help you understand what is going on in every step.
/**
*
* Modern method of connecting to a MySQL database and keeping it simple.
*
* If you would like to learn more about PDO,
* please visit http://php.net/manual/en/book.pdo.php
*
*/
//Set up database connection constants, so they cannot be changed.
define('DBHOST','127.0.0.1'); //Change this to the ip address of your database
define('DBNAME','test'); // Change this to the database name you are trying to connect to.
define('DBUSER','databaseuser'); // Insure this user is not the root user!!!!
define('DBPASS','databasepassword'); // Insure this is not the root password!!!!
//Let's try to connect to the database first.
try {
//Initiate a new PDO object called $MYDB and pass it the proper information to make
//the connection
$MYDB = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME."", DBUSER, DBPASS);
//If we are successful show it :D for the test page, if this is for production you should not show this.
echo "Database connection was successful.";
//If this does not worth catch the exception thrown by PDO so we can use it.
} catch(PDOException $e) {
//Show that there was an issue connecting to the database. Do not be specific because,
//user's do not need to know the specific error that is causing a problem for security
//reasons.
echo "Oh, sorry there was an issue with your request please try again.";
//Since we had an issue connecting to the database we should log it, so we can review it.
error_log("Database Error" . $e->getMessage());
}
//Since this is 100% php code we do not need to add a closing php tag
//Visit http://php.net/manual/en/language.basic-syntax.phptags.php for more information.
If you have any issues with this please attempt to break it up into smaller pieces while reviewing the PDO documentation.

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

sqlite correct path/URI for php pdo on windows

[ante-scriptum : this is a self answered question, you don't need to bother answering]
I ran into a weird configuration problem, not documented anywhere on the specific PHP.net page or at StackOverflow.
The problem
When opening an existing sqlite database on Windows, the same error kept showing :
SQLSTATE[HY000] [14] Unable To Open Database File
Although the code executed was copy/pasted from the manual :
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'sqlite:/full/path/to/db';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
I could not open this database, as I had tried all kinds of various DSN while googling :
$dsn = 'sqlite:/c:\\full\\path\\to\\db'; // --FAILED--
$dsn = 'sqlite://c:/full/path/to/db'; // --FAILED--
The solution
Notice the simple slash in the DSN sqlite:/ ? Just drop it !
write your DSN like this :
sqlite:name.db.
This works with relative and absolute paths so :
$dsn = 'sqlite:c:\full\path\to\name.db'; // --WORKS--
$dsn = 'sqlite:..\data\name.db'; // --WORKS--
$dsn = 'sqlite:name.db'; // --WORKS--
Hope it will save you some time in the future !
Just a small append to #justin answer:
You can also use the linux path style on windows:
$dsn = 'sqlite:c:/full/path/to/name.db';
Better than PDO('sqlite:...') is to use PHP sqlite3 extension and its SQLite3 class. I have tried your advices above with a database on an external (hard)drive and it didn't work (still giving the same error as mentioned in the first post by #justin-t). Then I tried with SQLite3 class and... Hurray! It worked!
(Just for those who are wondering about PDO and a lot of its weird bugs.)
Check if your PHP installation has enabled extensions for sqlite and/or sqlite3.
I've been struggling with a similar problem only to find that it rejected my DSN because sqlite was disabled.

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