PHP: Proper way of using a PDO database connection in a class
Posted
by Cortopasta
on Stack Overflow
See other posts from Stack Overflow
or by Cortopasta
Published on 2010-03-25T19:51:28Z
Indexed on
2010/03/25
19:53 UTC
Read the original article
Hit count: 480
Trying to organize all my code into classes, and I can't get the database queries to work inside a class. I tested it without the class wrapper, and it worked fine. Inside the class = no dice. What about my classes is messing this up?
class ac
{
public function dbConnect()
{
global $dbcon;
$dbInfo['server'] = "localhost";
$dbInfo['database'] = "sn";
$dbInfo['username'] = "sn";
$dbInfo['password'] = "password";
$con = "mysql:host=" . $dbInfo['server'] . "; dbname=" . $dbInfo['database'];
$dbcon = new PDO($con, $dbInfo['username'], $dbInfo['password']);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$error = $dbcon->errorInfo();
if($error[0] != "")
{
print "<p>DATABASE CONNECTION ERROR:</p>";
print_r($error);
}
}
public function authentication()
{
global $dbcon;
$plain_username = $_POST['username'];
$md5_password = md5($_POST['password']);
$ac = new ac();
if (is_int($ac->check_credentials($plain_username, $md5_password)))
{
?>
<p>Welcome!</p> <!--go to account manager here-->
<?php
}
else
{
?>
<p>Not a valid username and/or password. Please try again.</p>
<?php
unset($_POST['username']);
unset($_POST['password']);
$ui = new ui();
$ui->start();
}
}
private function check_credentials($plain_username, $md5_password)
{
global $dbcon;
$userid = $dbcon->prepare('SELECT id FROM users WHERE username = :username AND password = :password LIMIT 1');
$userid->bindParam(':username', $plain_username);
$userid->bindParam(':password', $md5_password);
$userid->execute();
print_r($dbcon->errorInfo());
$id = $userid->fetch();
Return $id;
}
}
And if it's any help, here's the class that's calling it:
require_once("ac/acclass.php");
$ac = new ac();
$ac->dbconnect();
class ui
{
public function start()
{
if ((!isset($_POST['username'])) && (!isset($_POST['password'])))
{
$ui = new ui();
$ui->loginform();
}
else
{
$ac = new ac();
$ac->authentication();
}
}
private function loginform()
{
?>
<form id="userlogin" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
User:<input type="text" name="username"/><br/>
Password:<input type="password" name="password"/><br/>
<input type="submit" value="submit"/>
</form>
<?php
}
}
© Stack Overflow or respective owner