I am trying the learn OOP PHP and PDO,it is a bit confusing for now. After reading lots of articles I decided to create my first project.And here is my code.
class db{
private static $instance = NULL;
private static $DSN = 'mysql:host=localhost;dbname=firstproject';
private function __construct(){
}
public static function getInstance(){
if(!self::$instance){
self::$instance = new PDO(self::$DSN,'root','');
self::$instance->exec('SET NAMES utf8');
}
return self::$instance;
}
public function reg_insert($usr_name,$usr_password){
self::$instance->query("INSERT INTO users VALUES(null,'$usr_name','$usr_password')");
}
}
class insRegInfo{
private $username;
private $password;
public function __construct($username,$password){
$dbe = db::getInstance();
db::reg_insert($username,$password);
}
}
if(isset($_POST['register'])){
$reg = new getRegInfo($_POST['username'],$_POST['password']);
}
<head>
<title>PDO Database Project</title>
</head>
<body>
<form action="" method="post">
<p>
<label>User Name</label>
<input type="text" name="username"/>
</p>
<p>
<label>Password</label>
<input type="password" name="password"/>
</p>
<p>
<input type="submit" name="register" value="Register" />
</p>
</form>
</body>
So as you see it is a simple registration system. My question is,calling database class in another class like that, is it a true way or should I carry the insert function to database class, or maybe I need to define db class as parent and insRegInfo as child with extends method?
Which way is better or is it just depends to me?
I would start by using model/mapper. It's a very simple way to get plain objects and to be able to persist them to the database. It also avoids mixing database calls and code (persistence logic) in with functionality (application or business logic). Simple example:
I would also recommend using getters/setters, instead of direct member access, but this was just for simplicity of code... As you develop more models/mappers you will find common mapper functionality (saving, loading, deleting, finding) and you can refactor your code to contain the common logic so you don't have a bunch of copypasta.