I'm fairly new to MySQL and PHP, so bear with me. After some research, I found out...much to my distress...that apparently my site is hosted on a Windows server (by default) on GoDaddy which doesn't support PDO.
I just recently switched all database calls to use prepared statements through recommendation from another question I posted. I now find out that these aren't running and I'm getting a nasty error:
Fatal error: Uncaught exception 'PDOException' with message 'could not find driver' in D:\Hosting\8446415\html\ROOTFOLDER\php\Connect.php:8
Stack trace: #0 D:\Hosting\8446415\html\ROOTFOLDER\php\Connect.php(8): PDO->__construct('mysql:host=HOSTNAME', 'DBNAME', 'PASSWORD')
#1 D:\Hosting\8446415\html\ROOTFOLDER\admin.php(67): Connect->connect()
#2 {main} thrown in D:\Hosting\8446415\html\ROOTFOLDER\php\Connect.php on line 8
Here is Connect.php:
<?php
class Connect {
const expAddress = "HOSTNAME";
const expUser = "USERNAME";
const expPwd = "PASSWORD";
function connect() {
$db = new PDO('mysql:host='.self::expAddress.';dbname='.self::expUser.';charset=UTF-8', self::expUser, self::expPwd);
if(!$db) {
die("<p>Could not establish a connection to the database.</p>");
include('footer.php');
}
else {
return $db;
}
}
}
?>
So what is the fix here? I don't know what is supported, and I was told to shy away from all mysql_* statements.
I cannot upgrade my hosting account to Linux, even though that would be easiest. Do I need to use mysqli_* statements? How would this particular call change so that the input is safe from injection?
$stmt = $db->prepare("SELECT * FROM logins WHERE username=? AND password=?");
$stmt->execute(array($user, $pass));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
You need to make sure you have pdo_mysql installed. Check phpinfo() for pdo_mysql ... if you know it's installed, you may just need to uncomment the extension=php_pdo_mysql.dll in php.ini ...
To catch your create error and display it nicely, you can modify your code as such:
try{
$db = new PDO('mysql:host='.self::expAddress.';dbname='.self::expUser.';charset=UTF-8', self::expUser, self::expPwd);
} catch (PDOException $e) {
die('Connect Failed: ' . $e->getMessage());
}
return $db;
If you do have access to php.ini, make sure that this line is uncommented:
extension_dir = "ext"
Related
I've been trying to use a sqlite database (php with PDO), but have been running into a problem. Generally the commands work, and everything is fine (including storing files), but for some reason when I run these two commands (which have been simplified), I get the error
SQLSTATE[HY000]: General error: 5 database is locked
I've tried for a while, but have been unable to fix whatever is wrong. The code is below.
Things I've done:
Tried to put sleep(2) between commands
Found out that commenting either of the commands out will cause the error not to happen (which doesn't really help, as both commands must run)
Note that (unlike other problems I saw while looking at similar questions) the database operates correctly in other cases.
$db = new MyDB();
$STH = $db->catchMistakes('SELECT PASSWORD FROM USERS WHERE USERNAME = ?', "test");
$STH->fetchColumn();
$db->catchMistakes("UPDATE ISSUES SET NAME = ? WHERE NUM = ?", ["test", "1"]);
And here's the code for MyDB
public function catchMistakes($cmd, $params = []) {
if (!is_array($params)) {
$params = [$params];
}
try {
$DBH = new PDO("sqlite:" . DB);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$DBH->beginTransaction();
$query = $DBH->prepare($cmd);
$toReturn = $query->execute($params);
$DBH->commit();
return $query;
}
catch(PDOException $e) {
$DBH->rollback();
$error = $e->getMessage();
exit;
}
}
Sorry if there's a simple fix, I'm pretty new at this. Any help would be greatly appreciated.
You can use closeCursor() method on a PDOStatement object to free the connection to the database so the statement can be executed. You can refer to the PHP manual.
I just start learning about PDO, I need some help, I Installed PHPStorm, and I just start using it too, I already have a datbase on phpMyAdmin, I made this code, but it gives me an error
<?php
try {
$handler = new PDO ('mysql:localost;dbname=Database', 'root', 'password');
$handler -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOExeption $e)
{
die('Sorry, Database problem');
}
$query = $handler->query('select * from users');
while($r= $query->fetch())
{
echo $r['name'];
}
?>
here is the error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in C:\Users\user1\PhpstormProjects\PDO\pdo.php:11 Stack trace: #0 C:\Users\user1\PhpstormProjects\PDO\pdo.php(11): PDO->query('select * from u...') #1 {main} thrown in C:\Users\user1\PhpstormProjects\PDO\pdo.php on line 11.
Any help?
thanks in advance :).
Please make sure your database actually exists and that there are no spelling mistakes in your connection code.
Edit 1
I also noticed this issue with your connection I'm not sure if this is what is causing it but you need mysql:host= not just mysql:localhost. Also you have a spelling mistake localost.
Change this,
$handler = new PDO ('mysql:localost;dbname=Database', 'root', 'password');
To,
$handler = new PDO('mysql:host=localhost;dbname=myDb', $username, $password);
replace the handler declaration for this:
$handler = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
where myDatabase is the one you will be using as default..
I am trying to get results from an API call using Slim connecting with MSSQLSERVER2012
the example used to work with MYSQL getconnection function (see below) but when I am trying to
connect with MsSQL server 2012 I am getting an error like "api call error "invalid data source name"
http://localhost/msapi/api.php/clients
1'api call error "invalid data source name"
require '/Slim/Slim.php';
$app = new Slim();
$app->get('/clients', 'getClients');
$app->run();
function getClients() {
$sql = "select * FROM clients";
try {
$db = getConnection();
$stmt = $db->query($sql);
$clients = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"client": ' . json_encode($clients) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function getConnection_MYSQL() {
$dbhost="SERVER";
$dbuser="USER";
$dbpass="PASSWORD";
$dbname="DB";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function getConnection() {
$dbhost="SERVER";
$dbuser="USER";
$dbpass="PASSWORD";
$dbname="DB";
$dbh = new PDO ("ADODB.Connection");
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$dbhost.";UID=".$dbuser.";PWD=".$dbpass.";DATABASE=".$dbname;
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->open($connStr); //Open the connection to the database
return $dbh;
}
the function getConnection_MYSQL() is an example that works.
But the getConnection() tryis to connect with MS SQL server ?
Do you see why I am getting an "invalid data source name" with the function getConnection()?
Since you didn't post an alternative DSN-string, I'm assuming you are using the one from your example and just replace host, username and password. This won't work.
When you are running your Slim-application on a windows host you can (and should) use Microsoft's SQL Server Driver for PHP (sqlsrv).
There are 2 versions sqlsrv.dll and pdo_sqlsrv.dll. When you want to reuse most of your code you should use the latter. This way you probably only have to modify your DSN (see php docs):
new PDO("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");
If you are using the first you have to update the way you connect to the db and create the query. You can read the Beginner's Guide to see a few examples that should make it easy.
If you are running not running your application on a Windows-machine you will probably have to set up ODBC and FreeTDS and then use PDO with an ODBC-DSN. From my experience this will be quite a lot of work, but there are a few good tutorials out there. Just google for "freetds sql server".
I have an Oracle database that I am trying to connect to.
For some reason when I try the following code:
<?php
include "header.php";
// simply attempt to connect to the database
/* If you are connecting to the Oracle database, the credentials are as follows:
* Username: ********
* Password: ********
* Hostname: **********
* Port: 1521
* Service name: ***********
*/
$oracleConnect = true;
if ($oracleConnect)
{
echo 'Attempting connection...<br>';
$connection = null;
try
{
$connection = oci_connect('user',
'pass',
'user#//hostname:1521/dbname');
}
catch (Exception $e)
{
echo $e->getMessage();
}
if (!$connection)
{
echo '<p>Something is wrong.</p>';
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// if the connection has been established
else
{
// tell the user and close it (this is a test)
echo 'Connection established!!';
oci_close($connection);
}
}
else
{
$connection = new mysqli('host', 'user', 'password', 'database');
echo ($connection) ? 'Database connection successful!' : 'Could not connect.';
}
include "footer.php";
?>
When I try the above code, I get the "Attempting connection..." to print, but nothing else. It is supposed to print something else regardless. What could possibly be going wrong?
I think the problem is the user# part of your connection string. I dont think thats necessary as oci_connect has a user name parameter. I could be wrong, ive never used oracle from php before, but the docs on oci connections would also seem to indicate that:
To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.
Also oci_connect does not throw an exception as far as i can tell so your try/catch is useless unless you planned on throwing your own when it returns false.
I am using Zend Framework and my application works on localhost but produces the can't connect to MySQL server error when I'm trying to connect to the database I've uploaded on a live server. I've tried handling exceptions and Zend_Exception catches it("perhaps factory() failed to load the specified Adapter class"). I've emailed the webmaster and he told me that Phpmyadmin is working fine so there should be no problem with connecting php to mysql. What else can I do? The lines that produce the error are the following:
$db = Zend_Registry::get('db');
$sql = 'SELECT * FROM department';
$result = $db->fetchAll($sql);
Is there something specific I can ask the webmaster to look at?
EDIT:
in my bootstrap:
public function _initDB()
{
$dbOptions = $this->getOption('db');
$db = Zend_Db::factory($dbOptions['adapter'], $dbOptions['params']);
Zend_Registry::set('db', $db);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
}
in my application.ini:
db.adapter = PDO_MYSQL
db.params.host = agila.upm.edu.ph
db.params.username = FacultyDB
db.params.password = *********
db.params.dbname = FacultyDB
Since you are convinced the settings are ok in application.ini are you initialising your db in bootstrap?
protected function _initDb() {
$registry = Zend_Registry::getInstance();
$db = Zend_Db::factory($registry->config->db->adapter,
$registry->config->db->database->toArray());
Zend_Db_Table::setDefaultAdapter($db);
Zend_Registry::set('db', $db);
}
try that in application.ini:
[db]
adapter = PDO_MYSQL
database.host = agila.upm.edu.ph
database.username = FacultyDB
database.password = *********
database.dbname = FacultyDB
Try configuring with that and my bootstrap code and see if it now works. I remember something about zend_db being picky about configuration from application.ini. I could be wrong its vague.