Call to undefined function query() - using PDO in PHP - 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.

Related

How to connect to mysql database with php?

I'm using Jetbrains and Mysql to work on this practical project, but when I connect to the mysql
database it gives me the following error:
C:\wamp64\bin\php\php5.6.40\php.exe C:\wamp64\www\Social_Network\Includes\connection.php
Connection failed: SQLSTATE[HY000] [1049] Unknown database 'social_network'
Process finished with exit code 0
I made sure several times that the database name is the same name and there are
no spelling errors at all (I copy pasted it from the database)
Here's my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=social_network", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
//?>
Welll, there's little that can be done about it. MySQL thinks that the database does not exist.
is the server the correct one?
is the case sensitivity set correctly? "Social_Network" and "social_network" might be considered different.
can you access the database with those parameters using a different tool (e.g. HeidiSQL, SQLYog, SQLterm, in a pinch even phpMyAdmin)?
Actually, JetBrains PHPStorm has a SQL terminal utility that can diagnose the connection. You may want to use it (once it knows what database you're connecting to, it will also warn you of several possible errors such as using the wrong table name or column name).

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.

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.

php mysql_connect - Lost connection to MySQL server

this post has been edited to reflect the findings thus far between myself and iamkrillin, as we have been the only two posters
I have the following VB.NET code connecting correctly, running from my PC
Dim strConnection As String = "Server=dev.xxxxx.vmc;Database=report1;integrated security=SSPI;" & _
"persist security info=False;Trusted_Connection=Yes;"
Dim ObjDa As SqlDataAdapter = New SqlDataAdapter(pStrQuery, strConnection)
Try
Dim dsReturn As DataSet = New DataSet
ObjDa.Fill(dsReturn)
ObjDa.Dispose()
Return dsReturn
Catch ex As Exception
Return Nothing
End Try
I have the following PHP code running from our iSeries
$conn = array( 'host' => 'dev.xxxxx.vmc',
'username' => 'vmc\adam',
'password' => 'xxxxxx)',
'dbname' => 'report1',
'pdoType' => 'dblib' );
try {
$db = new Zend_Db_Adapter_Pdo_Mssql($conn);
$db->getConnection();
} catch (Zend_Db_Adapter_Exception $e) {
}
The getConnection function, is throwing an error:
SQLSTATE[] (null) (severity 0)
And when I look up this error HERE, it appears to be a bug PRE 5.2.10, and we are running 5.2.17. But, some of the other comments say it is still a bug in 5.3.
*edit
It seems that if using a domain account, windows auth must be enabled. However, it is not through our PHP. So I need to set up a database specific user for our PHP connection.
In your VB snippet, you are connecting to SQL Server, and in your PHP snippet you are connecting to MySQL. If you need to use SQL Server from PHP, look at this. If you are on a non windows platform you can try FreeTDS. Here is an example of how to get started with it

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.

Categories