Weird PHP PDO Error - php

<?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(...);

Related

PHP Exits When I Try to Connect to a Database Using MySQLi

I have been developing a website recently, and I came across an error. When I tried to do print_r(error_get_last()); It output some text about mysql not being supported anymore, and to use MySQLi. I was all for it. When I edited my database class to support MySQLi, it exits every time it tries to connect. I have put echo 'hi<br />'; before and after the mysqli function, and a or trigger_error("Error: " . print_r(error_get_last())); at the end of it, but all it outputs is hi, and nothing else. My database is created in phpMyAdmin, and has all the correct permissions, but it just cannot connect. This is my connection code:
echo 'hi<br />';
$this->db = mysqli($host, $dbuser, $dbpass, $dbname) or trigger_error("Error: " . print_r(error_get_last()));
echo 'hi<br />';
$this->connect_start = microtime(true);
if ($this->db->connect_errno > 0) die ($this->debug(true));
It is in the constructor of a class that looks like this:
function db($host, $dbname, $dbpass, $dbuser)
and it is called like this:
$db = new db($host, $dbname, $dbpass, $dbuser);
Change this:
$this->db = mysqli()
to
$this->db = new mysqli()
mysqli is not a function, it's a class. If you had error reporting on you'd get a message like this:
PHP Fatal error: Call to undefined function mysqli()
That's the reason why the rest of your code isn't executed, the execution stops right there.
Also note that new mysqli() will never return false, so your or ... part becomes useless. If you want to check for connection errors you have to check $this->db->connect_error after the connection attempt.

PHP PDO drivers

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

Different ways to create a Connect Function in a Class? [duplicate]

This question already has answers here:
How to properly set up a PDO connection
(5 answers)
Closed 9 years ago.
Okay so I have some what of a dumb question, I've seen tuts and different things on making a CMS and I want to make an oop CMS, and I was wondering if someone could explain to me what the difference was between using one of the two examples?
Ex 1 -
class myClass
{
var $username;
var $password;
public function connect()
{
try {
$pdo = new PDO('mysql:host=localhost;dbname=dbname', $this->username,
$this->password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
// Then to call that function
$obj = new myClass();
$obj->username = "root";
$obj->password = "password";
$pdo = $obj->connect();
// Then run my query down here
Ex 2 -
class database
{
protected $connection = null;
//make a connection
public function __construct($hostname,$dbname,$username,$password)
{
try {
//MySQL with PDO_MYSQL
$this->connection = new PDO("mysql:host=$hostname;dbname=$dbname",
$username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$this->connection = null;
die($e->getMessage());
}
}
}
Or I've even seen people use a __construct then a seperate connect function
So what exactly is the difference? Is there a performance benefit by doing it a particular way? Or is there a way that is more correct than the other or are all three if these incorrect ways of doing it? I haven't found a reliable source to find an answer.
For the most cases 3rd example is the best:
In fact, PDO is already a database class. So, if you have no particular reason to create another on top of it, PDO itelf is just a perfect:
$pdo = new PDO('mysql:host=localhost;dbname=dbname', $username,$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
is all you actually need.
There are no noticeable performance differences between the two.
The second way is preferred by a lot of people because a database object would be kind of useless if it didn't try to connect to a database. Because attempting to connect to a database is so vital to the object's worth / existence, it makes sense to send in the connection details via the constructor so that it can attempt a connection as soon as it is being instantiated. Thus, changing:
$obj = new myClass();
$obj->username = "root";
$obj->password = "password";
$pdo = $obj->connect();
to
$obj = new myClass('localhost', 'root', 'mypassword');

No database selected inside function, what the solution with PDO?

I'm attempting to perform a query inside a function but it return me "No database selected". I regularly have re-initialized the PDO object inside it
$db = "mysql:host=localhost;dbname=my_database";
$pdo = new PDO($db, 'dbname', 'dbpassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//some operations.. Works fine!
function sendMail($to)
{
$db = "mysql:host=localhost;dbname=my_database";
$pdo = new PDO($db, 'dbname', 'dbpassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$qryString="SELECT Codice FROM users WHERE Mail=:mail";
$qry = $pdo->prepare($qryString);
$params = array("mail" => $to);
$qry->execute($params); //won't work
}
Note that operations on the DB outside the function works fine.
The problem is that the code won't work neither passing the global $pdo object.
This is the actual code
$db = "mysql:host=localhost;dbname=my_database";
$pdo = new PDO($db, 'dbname', 'dbpassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
sendMail($mail, $pdo)
function sendMail($to, PDO $pdo)
{
$qryString="SELECT Codice FROM users WHERE Mail=:mail";
$qry = $pdo->prepare($qryString);
$params = array("mail" => $to);
$qry->execute($params);
}
Variable scope has absolutely nothing to do with database connection details.
If you have a connection where database selected, the same database will be selected if you are using this connection inside a function.
So, this is a clear case of too localized question, as the problem is obviously of typo-like - connecting to wrong database, misspelling variable name, database name and such.
Unfortunately, regular PHP user has very little knowledge on performing correct, reproduceable experiment to prove their assumption. Instead, they guess the reason by indirect consequences.
You just have to write the code you told us about and see that database is selected all right. And then turn to search for real reason. Full error reporting (E_ALL) often helps a lot.
Pass the PDO object to the function, because the scope of $pdo is outside the scope of sendMail().
function sendMail(PDO $pdo, $to) {
$queryString = "SELECT Codice FROM users WHERE Mail=:mail";
$statement = $pdo->prepare($queryString);
$params = array("mail" => $to);
$result = $statement->execute($params);
}
or
function sendMail($to) {
global $pdo;
$queryString = "SELECT Codice FROM users WHERE Mail=:mail";
$statement = $pdo->prepare($queryString);
$params = array("mail" => $to);
$result = $statement->execute($params);
}

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.

Categories