1~

Minter Coder's Blog

22-PHP'de PDO ile veritabanı bağlantısı & Pagination (Sayfalama)

22-PHP PDO

PDO ile veritabanı bağlantısı

-- baglan.php

<?php 
  try{
      $db = new PDO('mysql:host=localhost;dbname=DB_ISMI,'USERNAME','PASSWORD');
  }catch(PDOException $e){
      $e->getMessage();
  }
?>

PDO ile CREATE

insert.php

<?php 
    $sorgu = $db->prepare("INSERT INTO tablo_ismi SET column_ismi=[value]");
    $ekle = $sorgu->execute([
        value
    ]);
    if($ekle){
        echo "Veriler eklendi";
    }else {
        $hata = $sorgu->errorInfo();
        echo "MySQL Hatası : " . $hata[2];
    }
?>

PDO ile READ

select.php

<?php 
    /*$sorgu = $db->prepare("SELECT * FROM tablo_ismi WHERE column_ismi = [value]");
    $sorgu->execute([
        value
    ]);
    $ders = $sorgu->fetch(PDO::FETCH_ASSOC);*/

    $sorgu = $db->prepare("SELECT * FROM tablo_ismi");
    $sorgu->execute();
    $dersler = $sorgu->fetchAll(PDO::FETCH_ASSOC);


    print_r($dersler);
?>

PDO ile UPDATE

<?php 
    $sorgu = $db->prepare("UPDATE tablo_ismi SET column_ismi=[value_1] WHERE column_ismi=[value_2]");
    $guncelle = $sorgu->execute([
        value_1,value_2
    ]);
    if ($guncelle){
        echo "Güncelleme başarılı";
    }else {
        echo "Güncelleme başarılı değil";
    }
?>

PDO ile DELETE

<?php 
    $sorgu = $db->prepare("DELETE FROM tablo_ismi WHERE column_ismi = [value_1]");
    $delete = $sorgu->execute([
        value_1
    ]);
?>

PDO Pagination

// PDO SAYFALAMA


    // Limit (sayfa içinde kaç ver görünecek)
    $limit = 5;

    // sayfa sayısı (kaçıncı sayfadayız ?)
    $sayfa = isset($_GET["sayfa"]) && is_numeric($_GET["sayfa"]) ? $_GET["sayfa"] : 1;
    if ($sayfa <= 0){
        $sayfa = 1;
    }
    // toplam veri (Veritabanından çekilecek)
    $toplamVeri = 50;
    /* 
        $toplamVeri = $db-query('SELECT count(id) as toplam FROM tablo_ismi)->fetch(PDO::FETCH_ASSOC)["toplam"];
    */

    // toplam sayfa sayısı
    $toplamSayfa = ceil($toplamVeri / $limit);

    // veriler kaçtan başlayacak
    $baslangic = ($sayfa * $limit) - $limit;

    // verileri listeleme
    $sorgu = $db->query("SELECT * FROM tablo_ismi ORDER BY id DESC LIMIT $baslangic,$limit")->fetchAll(PDO::FETCH_ASSOC);

    foreach($sorgu as $veri){
        echo $veri["veri_icerigi"];
    }

    $sol = $sayfa-3;
    $sag = $sayfa+3;

    if ($sayfa<=3){
        $sag = 7;
    }
    if ($sag > $toplamSayfa){
        $sol = $toplamSayfa - 6;
    }
    // sayfaları listeleme
    for ($i = $sol;$i<=$sag;$i++){
        if ($i>0 && $i<$toplamSayfa){
            echo '<a '.($i==$sayfa? ' class"active"' : null).' href="index.php?sayfa='.$i.'">'.$i.'</a>';
        }
    }