Advertisement
MICHAELCODE

Insert

Jul 11th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.28 KB | None | 0 0
  1. //Create a folder in you directory call it settings
  2. //Inside it create a file call it db_connection_setting.ini
  3. //Inside the file write below code
  4.  
  5. host = localhost
  6. schema = name_of_your_database
  7. username = database_username
  8. password = database_password
  9. charset = utf8
  10.  
  11.  
  12. //Create Connection Class Call it dbConn.php
  13.  
  14. class dbConn {
  15.  
  16.  
  17.     private $file_settings = 'settings/db_connection_setting.ini';
  18.     public $conn;
  19.  
  20.     // get the database connection
  21.     public function getConnection(){
  22.         $this->conn = null;
  23.         if (!$settings = parse_ini_file($this->file_settings, TRUE)) throw new exception('Unable to open ' . $this->file_settings . '.');
  24.         $dsn = "mysql:host=".$settings['host'].";dbname=".$settings['schema'].";charset=".$settings['charset']."";
  25.         $opt = [
  26.             PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
  27.             PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  28.             PDO::ATTR_EMULATE_PREPARES   => false,
  29.         ];
  30.         try{
  31.             $this->conn = new PDO($dsn,$settings['username'], $settings['password'], $opt);
  32.         }catch(PDOException $exception){
  33.             echo "Connection error: " . $exception->getMessage();
  34.         }
  35.         return $this->conn;
  36.     }
  37.  
  38. }
  39.  
  40.  
  41. //Create a function class file call it product.php
  42. // now inside this file paste below code
  43.  
  44. class product {
  45.     // database connection and table name
  46.     private $con;
  47.  
  48.     // object properties
  49.     public function __construct($db){
  50.         $this->con = $db;
  51.     }
  52.  
  53. public function getProductFromURL($id){
  54.    
  55.      // Better to use $stmt as the variable here, obviously this is subjective
  56.      // but will serve you better when you are working on other stmt objects
  57.      $stmt = $this->con->prepare("SELECT * FROM product_table WHERE product_id = :product_id ORDER BY ID");
  58.      $stmt->bindParam(':product_id', $id,PDO::PARAM_INT);
  59.      $stmt->execute();
  60.  
  61.      $results = $stmt->fetchAll(PDO::FETCH_OBJ);
  62.      return $results;
  63. }
  64.  
  65. }
  66.  
  67.  
  68. //Then to make use of this function inside your file call it this way
  69. include_once 'dbConn.php';
  70.  
  71. // instantiate database and objects
  72. $data = new dbConn ();
  73. $db = $data->getConnection();
  74. $get_product = new product($db);
  75. $get_product_by_id = $get_product->getProductFromURL($_GET['pid']);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement