Advertisement
Guest User

Untitled

a guest
Jan 7th, 2017
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. <?php
  2. class Connection {
  3. private $connection;
  4.  
  5. private $host='localhost';
  6. private $user='user';
  7. private $pass='pass';
  8. private $database='dbname';
  9. private $n=0;
  10.  
  11. function __construct() {
  12. $this->connection = mysqli_connect($this->host, $this->user, $this->pass, $this->database);
  13.  
  14. mysqli_query($this->connection,"SET NAMES 'utf8'");
  15. }
  16.  
  17. function sql($sql) {
  18. if (is_array($sql)) {
  19. foreach ($sql as $s) {
  20. $res = mysql_query($s);
  21. if (mysql_errno()) echo mysql_error().'<br>';
  22. $this->n++;
  23. }
  24. } else {
  25. $res = mysqli_query($this->connection,$sql);
  26. if (mysql_errno()) echo mysql_error().'<br>';
  27. $this->n++;
  28. }
  29. return $res;
  30. }
  31.  
  32. function __destruct() {
  33. if (is_resource($this->connection) )
  34. mysql_close($this->connection);
  35. }
  36.  
  37. function getLink() {
  38. return $this->connection;
  39. }
  40. }
  41.  
  42. So if I want to Create, Read, Update, Delete Something I do this:
  43. In another file: User.php (Which i want to use the new method I'm asking for and use prepared statements for the Queries here and escape functions)
  44. <?php
  45. // Declare a variable
  46. private $user;
  47.  
  48. // Setter
  49. function setUser($val){
  50. $this->user = $val;
  51. }
  52.  
  53. // Create Function to CreateUser
  54. function CreateUser(){
  55. $con = new Connection();
  56. $sql = "INSERT INTO user (DATA) VALUES(DATA)";
  57. $con->sql($sql);
  58. }
  59.  
  60. // Same for all CRUD i just change the Query of course.
  61.  
  62. ?>
  63.  
  64. <?php
  65. // At the index.php i do this:
  66. include_once 'User.php';
  67.  
  68. $user = new User();
  69.  
  70. if(isset($_POST['createUserButton'])){
  71. // $The variable i set in my User Class
  72. $user = $_POST['user'];
  73.  
  74. // Then the Setter
  75. $user->setUser($user);
  76.  
  77. // Then execute the Function
  78. $user->CreateUser();
  79. }
  80. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement