fork(3) download
  1. <?
  2. class Student {
  3. private $properties;
  4. function __construct($name, $age, $email){
  5. $name = strip_tags(trim($name));
  6. $email = strip_tags(trim($email));
  7. $age = (int)$age;
  8. $this->properties = array('name'=>$name, 'age'=>$age, 'email'=>$email);
  9. }
  10. function getInfo(){
  11. return $this->properties;
  12. }
  13. }
  14. class DataMapper {
  15. protected $db;
  16. function __construct($db){
  17. $this->db = $db;
  18. }
  19. function insertIntoDB(Student &$student){
  20. $query = "INSERT INTO tbl (name, age, email) VALUES (:name, :age, :email)";
  21. $stmt = $this->db->prepare($query);
  22. $info = $student->getInfo();
  23. $stmt->bindParam(':name', $this->db->quote($info['name']));
  24. $stmt->bindParam(':age', $this->db->quote($info['age']));
  25. $stmt->bindParam(':email', $this->db->quote($info['email']));
  26. $stmt->execute();
  27. }
  28. function selectFromDB(){
  29. //***
  30. }
  31. }
  32. $student = new Student($_POST['name'], $_POST['age'], $_POST['email']);
  33. $db = new PDO('mysql:host=localhost;dbname=test', 'root', '');
  34. $mapper = new DataMapper($db);
  35. $mapper->insertIntoDB($student);
Success #stdin #stdout 0.01s 24400KB
stdin
Standard input is empty
stdout
<?
class Student {
	private $properties;
	function __construct($name, $age, $email){
		$name = strip_tags(trim($name));
		$email = strip_tags(trim($email));
		$age = strip_tags(trim((int)$age));
		$this->properties = array('name'=>$name, 'age'=>$age, 'email'=>$email);
	}
	function getInfo(){
		return $this->properties;
	}
}
class DataMapper {
	protected $db;
	function __construct($db){
		$this->db = $db;
	}
	function insertToDB(Student &$student){
		$query = "INSERT INTO tbl (name, age, email) VALUES (:name, :age, :email)";
		$stmt = $this->db->prepare($query);
		$info = $student->getInfo();
		$stmt->bindParam(':name', $this->db->quote($info['name']));
		$stmt->bindParam(':age', $this->db->quote($info['age']));
		$stmt->bindParam(':email', $this->db->quote($info['email']));
		$stmt->execute();
	}
	function selectFromDB(){
		//***
	}
}
$student = new Student($_POST['name'], $_POST['age'], $_POST['email']);
$db = new PDO(parse_ini_file('config.ini'));
$mapper = new DataMapper($db);
$mapper->insertToDB($student);