v2.5.2
Giriş yap

OOP de yeniyim Db klasımda bi eksih varmı

bayburt
269 defa görüntülendi

OOP de yeniyim şöyle bir db klası yazdım bi hata göebiliyormusunuz teşekkurler

<?php
class Database {
    // Sınıfın tek örneğini tutacak statik değişken
    private static $instance = null;
    private $connection;

    // Veritabanı bağlantı bilgileri
    private $host = 'localhost';
    private $dbname = 'aa';
    private $username = 'asss';
    private $password = 'www';

    // Özel kurucu, dışarıdan yeni bir örnek oluşturulmasını engeller
    private function __construct() {
        try {
            $this->connection = new PDO("mysql:host={$this->host};dbname={$this->dbname};charset=utf8", $this->username, $this->password);
            $this->connection->exec("SET NAMES 'utf8'");
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $err) {
            echo '<h1><center><b>Db bağlantı hatası</b></center></h1>';
            // echo '<h1><center><b>' . $err->getMessage() . '</b></center></h1>';
            die(); // Hata durumunda işlemi sonlandır
        }
    }

    // Klonlamayı engellemek için private clone method
    private function __clone() {}

    // Serileştirmenin önüne geçmek için wakeup method ---incele
    public function __wakeup() {}

    // Sınıfın tek örneğini döndüren statik yöntem
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    // PDO bağlantısını döndüren yöntem
    public function getConnection() {
        return $this->connection;
    }
    
    public function q($p) {
        $stmt = $this->connection->query($p);
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    } 
    
    public function tekSatir($sql, $data = null) {
        $stmt = $this->connection->prepare($sql);
        $stmt->execute($data);
        return $stmt->fetch(PDO::FETCH_OBJ);
    }

    public function cokSatir($sql, $data = null) {
        $stmt = $this->connection->prepare($sql);
        $stmt->execute($data);
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }    
    
    public function esg($sql, $data) {
        $stmt = $this->connection->prepare($sql);
        $stmt->execute($data);
        return $stmt->rowCount(); // Etkilenen satır sayısını döndürür
    }    

    public function __destruct() {
        if ($this->connection !== null) {
            $this->connection = null; // PDO bağlantısını null yapmak (opsiyonel)
            unset($this->connection); // PDO bağlantısını kapatmak
        }
    }
}

function p($p){
	if(isset($_POST[$p])){
		return htmlentities(trim($_POST[$p]), ENT_QUOTES, FALSE, "UTF-8");
	}else {
		return null;
	}
}

function g($p){
	if(isset($_GET[$p])){
		return htmlentities(strip_tags(trim($_GET[$p])), ENT_QUOTES, FALSE, 'UTF-8');                    
	}else {
		return null;
	}
}    

function sslSifre($p, $mod = 0) {
	// Şifreleme algoritması ve anahtarını tanımla
	$alg = 'AES-128-ECB';
	$key = 'Bc2027***';

	if ($mod == 0) {
		$str = openssl_encrypt($p, $alg, $key);        
		return base64_encode($str); 
	} else if ($mod == 1) {
		$str = base64_decode($p);
		return openssl_decrypt($str, $alg, $key); 
	}
}

function txt($txt, $mod = null) {
	// Dönüşüm dizilerini ve kodlarını tanımlama
	$trChars =      array('Ç', 'ç', 'Ğ', 'ğ', 'ı', 'İ', 'Ö', 'ö', 'Ş', 'ş', 'Ü', 'ü');
	$htmlEntities = array('&Ccedil;', '&ccedil;', '&#286;', '&#287;', '&#305;', '&#304;', '&Ouml;', '&ouml;', '&#350;', '&#351;', '&Uuml;', '&uuml;');

	// Dönüşüm işlemlerini yap
	$transform = function ($text, $transliterator) use ($trChars, $htmlEntities) {
		$res = str_replace($htmlEntities, $trChars, $text);
		return Transliterator::create($transliterator)->transliterate($res);
	};

	switch ($mod) {
		case 'k':       return $transform($txt, 'tr-lower');
		case 'b':       return $transform($txt, 'tr-upper');
		case 'title':   return $transform($txt, 'tr-title');
		default:        return $transform($txt, '');
	}
}

$hata = (object)[
	'token'         =>  'Uzun süre işlem yapılmadığı için oturum sonlandırıldı.',
	'bosAlan'       =>  'Boş alan bıraktınız tüm alanların doldurulması zorunludur',
	'hataliMail'    =>  'Mail adresi geçersiz.',
	'kayitliMail'   =>  'Bu mail adresi sistemde kayıtlıdır başka bir mail adresi yazıp tekrar deneyiniz.',
	'banliUye'      =>  'Site yöneticisi sizi engelledi giriş yapamazsınız.',
	'sifreUyusmadi' =>  'Şifreler uyuşmuyor kontrol edip tekrar deneyiniz.',
];


Cevap yaz
Cevaplar (2)
acemi
125 gün önce

öncelikle tek satır çoksatır o tek bir metoda dönüştür ve çoklu kullanım haline getirmeni önericem

      public function fetch($query, $params = null, $fetchMethod = 'fetchAll')
    { 
        try {
            $sql = $query; 
            $stmt = $this->db->prepare($sql);
            if($params !== null):
                foreach ($params as $param => $value) {
                    $stmt->bindValue($param, $value);
                }
            endif;
            $stmt->execute();
            
            if ($fetchMethod === 'fetchAll') {
                return $stmt->fetchAll(PDO::FETCH_ASSOC);
            } elseif ($fetchMethod === 'fetch') {
                return $stmt->fetch(PDO::FETCH_ASSOC);
            } else {
                return false;  
            }
        } catch (PDOException $e) {
            echo "Hata: " . $e->getMessage();
            return false;
        }
    } 
    // toplam değerler için
    public function fetchTotal($sql, $params = [], $total = "total") { 
        return $this->fetch($sql, $params, "fetch")[$total];
    }

diğer bir konuda __constr... a direk değerleri ver bence başlatırken class a girip db bilgisi girmek ile uğraşma.

jct
134 gün önce

Sınıf yapısına bence

beginTransaction()
commit()
rollBack()

yapıları da eklenmeli