PHP PDO drivers - php

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..

Related

catching a 'PDOException' when database is down

I am trying to catch an error if I cannot connect to database (eg xamp down or database connection down etc). I have tried to use PDO::errorCode() but yield no reuslts.
In my php I have a connection.php and a method ' to connect to the datatbase many times and return a new PDO instance to achieve various queries. The response displays the error message then all the php queries that call it, which also includes the name and password of the database in a non encrypted format.
How can I catch this error and replace this error message with a human readable alternative (that doesnt display the name and password)?
CONNECTION.PHP
function connect()
{
// set database server access variables:
$host = "localhost";
$user = "root";
$pass = "password";
$dbase = "dbName";
//Establish a connection
$db = new PDO("mysql:host=".$host."; dbname=".$dbase."", $user, $pass); //line 16
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
return $db;
}
RESPONSE
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[HY000] [2002] No connection could be made because the target
machine actively refused it. ' in
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php:16
Stack trace: #0
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php(16):
PDO->__construct('mysql:host=loca...', 'root', 'password') #1
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\function\active-user.php(28):
connect() #2
D:\Users\Username\Dropbox\Web\htdocs\sitename\map-floorplan.php(10):
include('D:\Users\Username...') #3 {main} thrown in
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php
on line 16
do a try/catch to catch exceptions
try{
$db = new PDO("mysql:host=".$host."; dbname=".$dbase."", $user, $pass); //line 16
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
return $db;
} catch( PDOException $e){
$originalError = $e->getMessage();
echo 'something went wrong.. '.$originalError;
exit;
}

PDO::setAttribute() doesn't seems to affect new PDO()?

I have this code
try {
$dbh = new PDO('mysql:host=localhost;dbname=db_informations', 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
}
And it gives me the exception message:
SQLSTATE[HY000] [1049] Unknown database 'db_informations'
Because the correct name of my database is db_information only.
My question is, even if I don't include the line:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I still get the same exception and I think it's not necessary to use it? Is it?
This is simply because that's the behaviour of PDO::__construct() as you can read in the manual:
PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.
But if you don't set the error mode to Exception and you do:
try {
$dbh = new PDO('mysql:host=localhost;dbname=db_informations', 'root', '');
$dbh->query("SELECT * FROM aTableWhichDoesNotExists");
} catch(PDOException $e) {
echo $e->getMessage();
}
You won't get any excpetion message or error, because you didn't set the error mode. So you need to do this:
try {
$dbh = new PDO('mysql:host=localhost;dbname=db_informations', 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->query("SELECT * FROM aTableWhichDoesNotExists");
} catch(PDOException $e) {
echo $e->getMessage();
}
To receive an exception, which you then can catch:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.atablewhichdoesnotexists' doesn't exist
Also if you just think logically:
setAttribute() needs to be used with ->, which means you need an instance of the class to call that method. So how would you be able to call that method, if the instance couldn't be created correctly?
(So that would mean setAttribute() would have to bee static, so that you can set something/call it before you take the instance of the class)

PDO Error In SignUp Class

I'm working on my own SignUp class but it seems I have a problem with the PDO calls
The browser returns this to me:
Fatal error: Call to a member function query() on a non-object
I have my database configuration in a file included then on the main page. It's as follows:
<?
$dsn = 'mysql:dbname=magazin-online;host=localhost;';
$username = 'root';
$password = '';
try{
$pdo = new PDO($dsn, $username, $password);
}catch(PDOException $e){
echo 'Connection failed!: '.$e->getMessage();
}
An the line in the SignUp class causing the error is this:
$pdo->query("insert into ... () ... values ());
Now, I don't make any db connection in my SignUp class because I already included the file resposible for it.
How can I get rid of that error?
try using exec instead of query:
$pdo->exec("insert into ... () ... values ());
You are catching the exception generated by the new PDO, and then continue execution.
By doing it this way, you have to check that the class exists, so change:
if( $pdo)
$pdo->query("insert into ... () ... values ());
But .. a better way is not to continue execution after a critical error like this.
So better change the connection like this:
$dsn = 'mysql:dbname=magazin-online;host=localhost;';
$username = 'root';
$password = '';
try{
$pdo = new PDO($dsn, $username, $password);
}catch(PDOException $e){
echo 'Connection failed!: '.$e->getMessage();
die;
}
If I understand correctly, $pdo is a global variable. If you are calling $pdo->query inside a function, you either have to pass the $pdo connection as a parameter or declare it as global
global $pdo;
in the beginning of the member function.

PDOException on Windows Server

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"

Weird PHP PDO Error

<?php
require_once('inc/dbc1.php');
$dsn = 'mysql:dbname=somedb;host=somehost';
$user = 'someuser';
$password = 'somepass';
$pdo1 = new PDO($dsn, $user, $password);
$pdo1->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth1 = $pdo1->prepare('SELECT pID, lname, fname FROM Professor ORDER BY pID DESC LIMIT 5;');
$sth1->execute(array());
?>
Fatal error: Class 'PDO' not found on line 7
Line 7 is: $pdo1 = new PDO($dsn, $user, $password);
Why does this give this error and how do I fix it? All I'm trying to do is connect with the credentials and run that query
$pdo1 = new PDO($dsn, $user, $password);
PHP is looking for the class PDO on this line, I'm assuming it is in the file you included. Check to make sure it's the right file. PHP can't find the class definition. Maybe, make sure it is spelled correctly too.
If you're using a newer PHP version, you might have to prefix global classes with the global namespace identifier: "\"
So it would become: $pdo1 = new \Pdo(...);

Categories