pdo e sistema crud

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
Salve, sto provando una classe ma ho un problema non di mal funzionamento ma di funzionamento della classe.
ho questa classe:
PHP:
<?php
/**
 * CRUD Class 
 * 
 * @author      Jesse Boyer
 * @version     1.0a
 * @copyright   free for all
 * 
 * @usage

    // Construct
    $crud = new CRUD('mysql', 'demo', 'localhost', 'root');
    $crud->table = 'phone';
 
    // Insert
    $crud->insert(['name' => 'General', 'brand_id' => 2]);

    // Delete
    $crud->delete(11);
    $crud->delete(['name' => 'General']);

    // Update
    $crud->update(['name' => 'WORD'], 2);
    $crud->update(['name' => '123'], ['brand_id' => 1]);

    // Select
    $crud->select('phone_id, name', 2);
    $crud->select('phone_id, name', ['brand_id' => 2]);
    $crud->select(['phone_id', 'name'], ['brand_id' => 2]);
 */
 
// Database: CRUD
class CRUD extends PDO
{

    // Define the table to use
    public $table = null;
    
    // ------------------------------------------------------------------------
    
    /**
     * Instantiate a PDO Instance with CRUD functionality
     * 
     * @param string $db_type
     * @param string $db_name
     * @param string $db_host
     * @param string $db_user
     * @param string $db_pass
     * 
     * @return void
     */
    public function __construct($db_type, $db_name, $db_host, $db_user, $db_pass = '') 
    {
        try {
            $dsn = "$db_type:dbname=$db_name;host=$db_host";
            parent::__construct($dsn, $db_user, $db_pass);
            $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch(PDOException $e) {
            die($e->getMessage());
        }
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * Select
     * 
     * @param mixed $columns String or Array
     * @param array $data Must be Associative Array ['Column' => 'Value']
     * 
     * @return array
     */
    public function select($columns, $where = null) {
        $this->_isTableSet();
        
        if (is_array($columns)) {
            $columns = implode(',', $columns);
        }
        
        // Build the WHERE Statement
        $where_stmt = $this->_whereBuilder($where);
        if (!is_array($where)) {
            $where = ['primary_key' => $where];
        }
        
        // Run the Query
        $stmt = $this->prepare("SELECT $columns FROM `{$this->table}` $where_stmt");
        $stmt->execute($where);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * Inserts data into database
     * 
     * @param array $data Must be Associative Array ['Column' => 'Value']
     * 
     * @return mixed Boolean or insertID
     */
    public function insert($data) 
    {
        $this->_isTableSet();
        
        $keys_array = array_keys($data);
        $keys       = '`' . implode('`, `', $keys_array) . '`';
        $params     = ':' . implode(', :', $keys_array);
        
        $sth = $this->prepare("INSERT INTO `{$this->table}` ($keys) VALUES($params)");
        $result = $sth->execute($data);
        
        if ($result == 1) {
            return $this->lastInsertId();
        }

        return false;
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * Update
     * 
     * @param array $data   Associate key/value pairs to changes
     * @param mixed $where  Either an array or a numeric primary key index
     * 
     * @return integer Total affected rows
     */
    public function update($data, $where) {
        $this->_isTableSet();
        
        // Create the string for SET {here}
        $set = '';
        foreach ($data as $_key => $_value) {
            $set .= "`$_key` = :$_key,";
        }
        
        // Remove the trailing comma
        $set = rtrim($set, ',');
        
        // Build the WHERE Statement
        $where_stmt = $this->_whereBuilder($where);
        if (!is_array($where)) {
            $where = ['primary_key' => $where];
        }
        
        // Combine the DATA and WHERE to bind to both parameters
        $data = array_merge($data, $where);
        
        // Run the Query
        $sth = $this->prepare("UPDATE `{$this->table}` SET $set $where_stmt");
        $sth->execute($data);
        return $sth->rowCount();
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * Delete
     * 
     * @param mixed $where  Either an array or a numeric primary key index
     * 
     * @return boolean
     */
    public function delete($where) 
    {
        $this->_isTableSet();

        // Build the WHERE Statement
        $where_stmt = $this->_whereBuilder($where);
        if (!is_array($where)) {
            $where = ['primary_key' => $where];
        }
        
        // Tun the Query
        $sth = $this->prepare("DELETE FROM `{$this->table}` $where_stmt");
        $sth->execute($where);
        return $sth->rowCount();
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * Builds the MySQL WHERE Clause
     * 
     * @param mixed $where
     * 
     * @return mixed Could be empty or a where condition
     */
    private function _whereBuilder($where)
    {
        $where_stmt = null;
        if (is_numeric($where)) 
        {
            $primary = $this->table . '_id';
            $where_stmt = " WHERE `$primary` = :primary_key";
        }
        elseif (is_array($where)) 
        {
            // Build the Where Statement
            $where_stmt = '';
            foreach ($where as $_key => $_value) {
                $where_stmt .= "`$_key` = :$_key AND ";
            }
            $where_stmt = " WHERE " . rtrim($where_stmt, ' AND ');
        }
        return $where_stmt;
    }
    
    // ------------------------------------------------------------------------
    
    /**
     * Checks if the table has been set, this is required
     */
    private function _isTableSet() {
        if ($this->table == null) {
            die('You must set the $crud->table');
        }
    }
    
    // ------------------------------------------------------------------------
    
}
/** EOF */


ora il mio codice di test è questo:
PHP:
<?php
 include("crud.php");
 $crud = new CRUD('mysql', 'crud_test', 'localhost', 'root');
 $crud->table = 'rubrica';
 $rub = $crud->select('*');

 foreach($rub as $row)
 {
  echo $row["nome"]."\n";
  echo $row["cognome"];
 }
  $nome = "Luigi";
  $cognome = "Amorfini";
  $crud->insert(['nome' => ''.$nome.'', 'cognome' => ''.$cognome.'']);

?>

mi dite come posso usare il ciclo while invece del foreach?
Perché mi servirebbe anche il controllo dell'if per visualizzare singolo dato.

Mi dite come posso implementare in questa classe?

Grazie mille e buona domenica.
 
Discussioni simili
Autore Titolo Forum Risposte Data
L pdo (stampare un valore con ritorno a funzione) PHP 0
K [PHP] PDO.bindingParam PHP 2
M [PHP] Interrompere DROP TABLE con PDO PHP 0
M [PHP] Alternativa a datagrid con PDO PHP 6
M [PHP] Creare un menu a tendina con pdo PHP 18
M [PHP] Array di array - PDO PHP 2
3_g errore con mysql insert in PDO PHP 29
W [PHP] Creazione classe PDO PHP 4
F PHP, PDO e visualizzazioni errori e/o eccezioni PHP 3
3_g [PHP] mvc, pdo e classi... PHP 7
F Help-PDO copiare Database MySQL PHP 3
F php PDO mysql connessione(select_db) PHP 3
Fredyss redirect a altra pagina php dopo commit su postgresql con PDO PHP 1
K Non trovo l'errore! PDO MYSQL UPDATE PHP 2
C [PHP] PDO prepared statement - select query errore PHP 7
ANDREA20 [PHP] Errore $this->db_connection = new PDO PHP 0
CristianB72 Non riesco a connettermi al DB tramite PDO Database 10
MarcoGrazia [PHP][PDO][MySQL] Non registra ma non da nemmeno errori. PHP 0
MarcoGrazia [PHP][PDO] Come connettersi al database Snippet PHP 0
MarcoGrazia [PDO][PHP[MySQL] Piccolo modulo di ricerca in un sito tramite l'operatore LIKE Snippet PHP 1
neo996sps [PHP e funzioni con PDO] Funzione per generare corpo tabella PHP 1
Marco_88 fetchAll() PDO PHP 13
D Paginazione dati PDO PHP 8
N Problemi estrazione / visualizzazione immagini dal database con PDO PHP 2
R Organizzazione PHP Mysql PDO PHP 15
M PDO e mysqli PHP 1
MarcoGrazia [PDO][MySQL] L'update non avviene PHP 1
MarcoGrazia [PDO] insert che non inserisce e non da errori PHP 1
Monital PDO e connessioni a più database PHP 4
Monital Da mysql a PDO PHP 3
S PDO accertarsi del avvenimento della query PHP 1
voldemort PHP PDO: non c'ho capito niente PHP 1
L [RISOLTO]PDO if per "non ci sono dati" PHP 8
L Paginazione con pdo. PHP 8
L pdo con login PHP 2
L PDO : bindParam PHP 3
L login con pdo/mysql PHP 2
S Problema di login con PDO PHP 2
B Esercizio PDO PHP 20
B Pdo PHP 6
S Meglio mysqli o PDO ? PHP 2
borgo italia query con PDO PHP 11
borgo italia classe pdo PHP 9
M PDO prepare PHP 1
L da mysql a pdo PHP 4
F Sistema rilevazione presenze PHP 1
MarcoGrazia Sistema di news interno al sito PHP 3
T SSD - errore sistema Hardware 2
R Come creare sistema Add to homescreen PHP 3
L Sistema outdoor centralizzato IP Cam e Videosorveglianza 0

Discussioni simili