Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Create a folder in you directory call it settings
- //Inside it create a file call it db_connection_setting.ini
- //Inside the file write below code
- host = localhost
- schema = name_of_your_database
- username = database_username
- password = database_password
- charset = utf8
- //Create Connection Class Call it dbConn.php
- class dbConn {
- private $file_settings = 'settings/db_connection_setting.ini';
- public $conn;
- // get the database connection
- public function getConnection(){
- $this->conn = null;
- if (!$settings = parse_ini_file($this->file_settings, TRUE)) throw new exception('Unable to open ' . $this->file_settings . '.');
- $dsn = "mysql:host=".$settings['host'].";dbname=".$settings['schema'].";charset=".$settings['charset']."";
- $opt = [
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
- PDO::ATTR_EMULATE_PREPARES => false,
- ];
- try{
- $this->conn = new PDO($dsn,$settings['username'], $settings['password'], $opt);
- }catch(PDOException $exception){
- echo "Connection error: " . $exception->getMessage();
- }
- return $this->conn;
- }
- }
- //Create a function class file call it product.php
- // now inside this file paste below code
- class product {
- // database connection and table name
- private $con;
- // object properties
- public function __construct($db){
- $this->con = $db;
- }
- public function getProductFromURL($id){
- // Better to use $stmt as the variable here, obviously this is subjective
- // but will serve you better when you are working on other stmt objects
- $stmt = $this->con->prepare("SELECT * FROM product_table WHERE product_id = :product_id ORDER BY ID");
- $stmt->bindParam(':product_id', $id,PDO::PARAM_INT);
- $stmt->execute();
- $results = $stmt->fetchAll(PDO::FETCH_OBJ);
- return $results;
- }
- }
- //Then to make use of this function inside your file call it this way
- include_once 'dbConn.php';
- // instantiate database and objects
- $data = new dbConn ();
- $db = $data->getConnection();
- $get_product = new product($db);
- $get_product_by_id = $get_product->getProductFromURL($_GET['pid']);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement