Learning OOP in PHP, trying to refactor my code. Can't connect to database anymore
Thought I understood how classes work, then I tried this code:
class user
{
var $dbcon;
var $dbinfo;
var $con;
var $error;
function dbConnect()
{
$this->dbinfo['server'] = "localhost";
$this->dbinfo['database'] = "foolish_faith";
$this->dbinfo['user'] = "user";
$this->dbinfo['password'] = "password";
$this->con = "mysql:host=".$dbinfo['server']."; dbname=".$dbinfo['database'];
$this->dbcon = new PDO($con, $dbinfo['user'], $dbinfo['password']);
$this->dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->error = $this->dbcon->errorInfo();
if ($error[0] != "")
{
print "Error!";
print_r($error);
}
}
}
Now it just spits out this error:
Fatal error: Uncaught exception 'PDOException' with message 'invalid data source name' in E:\PortableApps\xampp\htdocs\dbcon.php:24 Stack trace: #0 E:\PortableApps\xampp\htdocs\dbcon.php(24): PDO->__construct('', NULL, NULL) #1 E:\PortableApps\x开发者_如何学Campp\htdocs\login.php(4): user->dbConnect() #2 {main} thrown in E:\PortableApps\xampp\htdocs\dbcon.php on line 24
Can anybody see what I'm doing wrong, as I'm sure it has to do with my lack of knowledge when it comes to classes?
$this->con = "mysql:host=".$dbinfo['server']."; dbname=".$dbinfo['database'];
$this->dbcon = new PDO($con, $dbinfo['user'], $dbinfo['password']);
When you acces variables of a class instance you have to use the -> operator. In this case you'd use $this->dbinfo
instead of just $dbinfo
and $this->con
instead of $con
. You've done it correctly on the left side, but missed some on the right.
Don't put spaces in your connection string. ("; dbname="
should be ";dbname="
).
Also, there are a couple of instances where you need to add a $this->
in front of some class instance variables ($this->con
, $this->dbinfo
et cetera).
Make this: $this->dbcon = new PDO($con, $dbinfo['user'], $dbinfo['password']);
Int this: $this->dbcon = new PDO($this->con, $dbinfo['user'], $dbinfo['password']);
Here is the dsn syntax : http://fr2.php.net/manual/en/ref.pdo-mysql.connection.php I don't see any space in it, maybe you should remove the one you added after the semicolon...
精彩评论