• 30-01-2010, 17:12:09
    #1
    Üyeliği durduruldu
    Merhabalar,
    Nesne tabanlı programlamaya yeni geçtim ve oop ile yapılmış bir veritabanından veri çekme ve yazdırma sınıfına ihtiyacım var.İnternette bulamadım.Daha önceden yazdığınız scriptlerden vs. sqlla birlikte paylaşırsanız memnun olurum.
  • 30-01-2010, 17:23:09
    #2
    Üyeliği durduruldu
    net.tutsplus.com sitesinden php bölümüne bakabilirsin.aşagıdaki kodlarda istediğinden fazlası var kolay gelsin
    <?php
    /*
     * File Name: Database.php
     * Date: November 18, 2008
     * Author: Angelo Rodrigues
     * Description: Contains database connection, result
     *              Management functions, input validation
     *
     *              All functions return true if completed
     *              successfully and false if an error
     *              occurred
     *
     */
    class Database
    {
    
        /*
         * Edit the following variables
         */
        private $db_host = 'localhost';     // Database Host
        private $db_user = 'root';          // Username
        private $db_pass = 'root';          // Password
        private $db_name = 'blog';          // Database
        /*
         * End edit
         */
    
        private $con = false;               // Checks to see if the connection is active
        private $result = array();          // Results that are returned from the query
    
        /*
         * Connects to the database, only one connection
         * allowed
         */
        public function connect()
        {
            if(!$this->con)
            {
                $myconn = @mysql_connect($this->db_host,$this->db_user,$this->db_pass);
                if($myconn)
                {
                    $seldb = @mysql_select_db($this->db_name,$myconn);
                    if($seldb)
                    {
                        $this->con = true;
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return true;
            }
        }
    
        /*
        * Changes the new database, sets all current results
        * to null
        */
        public function setDatabase($name)
        {
            if($this->con)
            {
                if(@mysql_close())
                {
                    $this->con = false;
                    $this->results = null;
                    $this->db_name = $name;
                    $this->connect();
                }
            }
    
        }
    
        /*
        * Checks to see if the table exists when performing
        * queries
        */
        private function tableExists($table)
        {
            $tablesInDb = @mysql_query('SHOW TABLES FROM '.$this->db_name.' LIKE "'.$table.'"');
            if($tablesInDb)
            {
                if(mysql_num_rows($tablesInDb)==1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    
        /*
        * Selects information from the database.
        * Required: table (the name of the table)
        * Optional: rows (the columns requested, separated by commas)
        *           where (column = value as a string)
        *           order (column DIRECTION as a string)
        */
        public function select($table, $rows = '*', $where = null, $order = null)
        {
            $q = 'SELECT '.$rows.' FROM '.$table;
            if($where != null)
                $q .= ' WHERE '.$where;
            if($order != null)
                $q .= ' ORDER BY '.$order;
    
            $query = @mysql_query($q);
            if($query)
            {
                $this->numResults = mysql_num_rows($query);
                for($i = 0; $i < $this->numResults; $i++)
                {
                    $r = mysql_fetch_array($query);
                    $key = array_keys($r);
                    for($x = 0; $x < count($key); $x++)
                    {
                        // Sanitizes keys so only alphavalues are allowed
                        if(!is_int($key[$x]))
                        {
                            if(mysql_num_rows($query) > 1)
                                $this->result[$i][$key[$x]] = $r[$key[$x]];
                            else if(mysql_num_rows($query) < 1)
                                $this->result = null;
                            else
                                $this->result[$key[$x]] = $r[$key[$x]];
                        }
                    }
                }
                return true;
            }
            else
            {
                return false;
            }
        }
    
        /*
        * Insert values into the table
        * Required: table (the name of the table)
        *           values (the values to be inserted)
        * Optional: rows (if values don't match the number of rows)
        */
        public function insert($table,$values,$rows = null)
        {
            if($this->tableExists($table))
            {
                $insert = 'INSERT INTO '.$table;
                if($rows != null)
                {
                    $insert .= ' ('.$rows.')';
                }
    
                for($i = 0; $i < count($values); $i++)
                {
                    if(is_string($values[$i]))
                        $values[$i] = '"'.$values[$i].'"';
                }
                $values = implode(',',$values);
                $insert .= ' VALUES ('.$values.')';
    
                $ins = @mysql_query($insert);
    
                if($ins)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    
        /*
        * Deletes table or records where condition is true
        * Required: table (the name of the table)
        * Optional: where (condition [column =  value])
        */
        public function delete($table,$where = null)
        {
            if($this->tableExists($table))
            {
                if($where == null)
                {
                    $delete = 'DELETE '.$table;
                }
                else
                {
                    $delete = 'DELETE FROM '.$table.' WHERE '.$where;
                }
                $del = @mysql_query($delete);
    
                if($del)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
    
        /*
         * Updates the database with the values sent
         * Required: table (the name of the table to be updated
         *           rows (the rows/values in a key/value array
         *           where (the row/condition in an array (row,condition) )
         */
        public function update($table,$rows,$where)
        {
            if($this->tableExists($table))
            {
                // Parse the where values
                // even values (including 0) contain the where rows
                // odd values contain the clauses for the row
                for($i = 0; $i < count($where); $i++)
                {
                    if($i%2 != 0)
                    {
                        if(is_string($where[$i]))
                        {
                            if(($i+1) != null)
                                $where[$i] = '"'.$where[$i].'" AND ';
                            else
                                $where[$i] = '"'.$where[$i].'"';
                        }
                    }
                }
                $where = implode('',$where);
    
    
                $update = 'UPDATE '.$table.' SET ';
                $keys = array_keys($rows);
                for($i = 0; $i < count($rows); $i++)
                {
                    if(is_string($rows[$keys[$i]]))
                    {
                        $update .= $keys[$i].'="'.$rows[$keys[$i]].'"';
                    }
                    else
                    {
                        $update .= $keys[$i].'='.$rows[$keys[$i]];
                    }
    
                    // Parse to add commas
                    if($i != count($rows)-1)
                    {
                        $update .= ',';
                    }
                }
                $update .= ' WHERE '.$where;
                $query = @mysql_query($update);
                if($query)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
    
        /*
        * Returns the result set
        */
        public function getResult()
        {
            return $this->result;
        }
    }
    ?>
  • 30-01-2010, 18:00:00
    #4
    Üyeliği durduruldu
    inceliyorum teşekkür ederim. replerinizi veriyorum.
  • 27-07-2010, 20:56:24
    #5
    Biraz geç oldu belki bu konuya cevap ama.. Kendim için ararken forumda da gördüm. Konusu hazırdı paylaşmak istedim..

    Önce db.php dosyasını aşağıdaki gibi oluşturalım.

    $user = "";
    $pass = "";
    $db = "";
    $hosst = "localhost";
    $mysqli = new mysqli($hosst,$user,$pass,$db);
    mysqli_report(MYSQLI_REPORT_ERROR);
    Daha Sonra farz edelim ki tablo1 'de ID,SUTUN1,SUTUN2 olsun bunu içinde

    include "db.php";
    $result = $mysqli->query("Select * From tablo1 ORDER by ID");
    echo "<table borde=1 cellpadding=10>";
    echo "<tr><th>ID</th><th>SUTUN1</th><th>SUTUN2</th>";
    while($row = $result->fetch_object())
    {
    echo "<tr>";   
    echo "<td>" . $row->ID . "</td>";
    echo "<td>" . $row->SUTUN1 . "</td>" ;
    echo "<td>" . $row->SUTUN2 . "</td>"; 
    echo "</tr>";
    }
    Hepsi bu kadar
  • 27-07-2010, 22:10:59
    #6
    biraz daha farklı yapıda bir sınıfım var. çalışma mantığı şöyle;
    veritabanında tablolarımız ve tablolarımıza karşılık gelen sınıflarımız var. kullanıcı tablosu için veritabanında id, kullaniciadi, sifre, eposta, adi, soyadi, sehir, adres, postakodu, telefon, websitesi, onay alanlarının olduğunu düşünürsek ona karşılık gelen php sınıfımızda
     class Kullanicis
    {
    
        public $id;
        public $kullaniciadi;
        public $sifre;
        public $eposta;
        public $adi;
        public $soyadi;
        public $sehir;
        public $adres;
        public $postakodu;
        public $telefon;
        public $websitesi;
        public $onay;
    	
    	function __construct()
    	{
    		$this->kullaniciadi = 'dene';
    	}
        
    }
    şeklinde oluyor. veritabanı sınıfı, kullanıcı sınıfındaki property adlarını okuyarak ilgili kaydı sizi sorgu yazmak sorunda bırakmadan kendisi ekleyebiliyor ve düzenleyebiliyor. kendi işlerimde lazım olduğu için bi ara yazmıştım ama yarım kaldı.
    <?php
    /**
     * @author İsmail Perim <http://ismailperim.net> <ismailperim@gmail.com>
     * @copyright 2009 © İsmail Perim <http://ismailperim.net> <ismailperim@gmail.com>
     * @license Licensed under the GNU General Public License, version 2. 
     * @license the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
     * @version $Id: genel.vtislem.php  2010-01-04 23:36:06$
     **/
     
     
    class VTIslem
    {
    	public $TabloAdi;
    	public $IslemTuru;
    	public $Sinif;
    	public $IslemDisi;
    	private $sinifDizi;
    	private $sinifOzellikleri;
    	private $tabloKolonlari;
    	
    	/**
          * VTIslem Sınıfı Constructor Fonksiyonu 
          * @param string $_tabloAdi
    	  * @param int $_islemTuru
    	  * @param object $_sinif
    	  * @param array $_islemDisi = array()
          **/
    	public function  __construct($_tabloAdi,$_islemTuru,$_sinif,$_islemDisi = array()) 
    	{
    		$this->TabloAdi = $_tabloAdi;
    		$this->IslemTuru = $_islemTuru;
    		$this->Sinif = $_sinif;
    		$this->IslemDisi = $_islemDisi;
    		$this->sinifDizi = (array)$this->Sinif;
    		$this->sinifOzellikleri = array_keys($this->sinifDizi);
    		
    		$kolonlar = mysql_query("SHOW COLUMNS FROM $this->TabloAdi ");
    		
    		$this->tabloKolonlari = array();
    		$say = 0;
    		while($satir = mysql_fetch_array($kolonlar))
    		{
    			$this->tabloKolonlari[$say]	= $satir['Field'];
    			$say++;
    		}
    		
    		
    		switch((int)$this->IslemTuru) 
    		{
    			case 1:
    				$this->Ekle();
    			break;
    			case 2:
    				$this->Duzenle();
    			break;
    			
    		}
    	}
    
    	/**
          * Düzenleme İşlemi
    	  * @return void
          **/	
    	private function Duzenle()
    	{
    		$sorguMetin = 'UPDATE '.$this->TabloAdi.' SET ';
    		
    		for($i = 0;$i<count($this->tabloKolonlari);$i++)
    		{
    			if(!in_array($this->tabloKolonlari[$i],$this->IslemDisi) && !in_array('@'.$this->tabloKolonlari[$i],$this->IslemDisi) )
    			{
    			
    				$sorguMetin .= $this->tabloKolonlari[$i] .' = '."'".$this->Sinif->{$this->tabloKolonlari[$i]}."'"; 
    				if($i<count($this->tabloKolonlari)-1)
    				{
    					if(!in_array($this->tabloKolonlari[$i+1],$this->IslemDisi))
    					{
    						$sorguMetin .= ' , ';
    					}	
    				}
    			}
    		}
    		for($i = 0;$i<count($this->IslemDisi);$i++)	
    		{
    			if(false !== strpos($this->IslemDisi[$i],'@'))
    			{
    						$islemDisiKey = substr($this->IslemDisi[$i],1);
    						$sorguMetin .= ' WHERE '.$islemDisiKey.' = '."'".$this->Sinif->{$islemDisiKey}."'";
    						break;
    			}
    		}
    		mysql_query($sorguMetin);
    	}
    	
    	/**
          * Ekleme İşlemi
    	  * @return void
          **/	
    	private function Ekle()
    	{
    		$sorguMetin = 'INSERT INTO '.$this->TabloAdi.'(';
    		
    		for($i = 0;$i<count($this->tabloKolonlari);$i++)
    		{
    			if(!in_array($this->tabloKolonlari[$i],$this->IslemDisi))
    			{
    			
    				$sorguMetin .= $this->tabloKolonlari[$i];
    				if($i<count($this->tabloKolonlari)-1)
    				{
    					if(!in_array($this->tabloKolonlari[$i+1],$this->IslemDisi))
    					{
    						$sorguMetin .= ',';
    					}	
    				}
    			
    			}
    		}
    		$sorguMetin .=') VALUES(';
    		for($g = 0;$g<count($this->tabloKolonlari);$g++)
    		{
    			if(!in_array($this->tabloKolonlari[$g],$this->IslemDisi))
    			{
    				$sorguMetin .= "'".$this->Sinif->{$this->tabloKolonlari[$g]}."'";
    				if($g<count($this->tabloKolonlari)-1)
    				{
    					if(!in_array($this->tabloKolonlari[$g+1],$this->IslemDisi))
    					{
    						$sorguMetin .= ',';
    					}	
    				}
    			
    			}
    		}
    		$sorguMetin .= ')';
    		
    		mysql_query($sorguMetin);
    	}
    	
    
    }
    ?>

    örnek kullanımı ise bir düzenleme işlemi için şöyle;

    <?php
    
    // mysql connection içeren sayfa
    include_once 'genel.baglanti.php';
    
    class Kullanicis
    {
    
        public $id;
        public $kullaniciadi;
        public $sifre;
        public $eposta;
        public $adi;
        public $soyadi;
        public $sehir;
        public $adres;
        public $postakodu;
        public $telefon;
        public $websitesi;
        public $onay;
    	
    	function __construct()
    	{
    		$this->kullaniciadi = 'dene';
    	}
        
    }
    
    
    $vt = new VTIslem('kullanicilar',2,new Kullanicis(),array('id','onay'));
    $vt->Ekle();
    
    ?>

    biraz yarım yamalak bir taslak ama fikir verici olabilir. kendi ihtiyacın doğrultusunda geliştirebilirsin.
  • 27-07-2010, 22:16:19
    #7
    Kimlik doğrulama veya yönetimden onay bekliyor.
    ezSQL kullan derim ben tüm scriptlerimde onu kullanıyorum.. Blogunu sürekli takip ettiğim Yakup ER arkadaşımız ezSQL'in nasıl kullanıldıgına dair güzel bir makale hazırlamış buradan inceleyebilirsiniz.
  • 28-07-2010, 09:21:01
    #8
    Üyeliği durduruldu
    HakanGEDICI adlı üyeden alıntı: mesajı görüntüle
    ezSQL kullan derim ben tüm scriptlerimde onu kullanıyorum.. Blogunu sürekli takip ettiğim Yakup ER arkadaşımız ezSQL'in nasıl kullanıldıgına dair güzel bir makale hazırlamış buradan inceleyebilirsiniz.
    teşekkürler, ben konuyu açalı bayağı oldu, şuandada ezsql kulanıyorum zaten.
  • 28-07-2010, 10:07:34
    #9
    Üyeliği durduruldu
    kendim bir tane yaziyordumda insert ve delete kismi kalmisti. yoksa aslinda veritabani icin Singleton tasarim sablonunu kullanmak gerek @BHCoder ustadin verdigi class cok basarili bu arada. direk kullanabilirsiniz