INSERT e UPDATE non funzionano

stefano862

Nuovo Utente
5 Dic 2013
26
0
0
Ciao, ho dei problemi nel mio codice ad interagire con in database. Le tabelle vengono create correttamente, le SELECT funzionano ma le INSERT e gli UPDATE no e non ne capisco il motivo.

In un file Database.php faccio:
PHP:
class Database {
   private static $instance = null;
   private static $dsn = "mysql:host=localhost;dbname=example"; 
   private static $username = 'root';
   private static $password = 'example';
   
   private $connection = null;
   
   private function __construct() {
      $this->connection = new PDO(static::$dsn, static::$username, static::$password);
   }
   
   public static function getInstance() {
      if(!static::$instance) {
         static::$instance = new Database();
      }
      return static::$instance;
   }
   
   public static function configConnection($dsn, $username, $password) {
      if(static::$instance) {
         throw new Exception("Connessione già stabilita.");
      }
      static::$dsn = $dsn;
      static::$username = $username;
      static::$password = $password;
   }
   
   public function connection() {
      return $this->connection;
   }
   
   public function exec($statement) {
      if($this->connection->exec($statement) === false) {
         throw new Exception("Database exec fallita.");
      }
   }
   
   public function prepare($statement) {
      $prepared = $this->connection->prepare($statement);
      $prepared->setFetchMode(PDO::FETCH_ASSOC);
      return $prepared;
   }
   
   public function lastInsertedId() {
      return $this->connection->lastInsertId();
   }
}

Per creare le varie tabelle faccio in questo modo:
PHP:
$db = Database::getInstance();
$query = "CREATE TABLE IF NOT EXISTS ex1 (
            id INTEGER(4) NOT NULL,
            ... ecc ...
            PRIMARY KEY(id)
         );"; 
$stmt = $db->prepare($query);
$stmt->execute();

Poi, per esempio, ho una classe User.php che implementa il metodo findUser($username) fatto così:
PHP:
public function findUser($username) {
   $db = Database::getInstance();
   $stmt = $db->prepare("SELECT * FROM `users` WHERE `username` = ?");
   $stmt->execute(array($username));
   $user = null;
   if($stmt->rowCount()) {
      $user = User::load($stmt->fetch());
   }
   return $user;
}
dove il metodo load(array $data) è:
PHP:
public static function load(array $data) {
   $u = new User();
   $u->id = $data['id'];
   $u->setUsername($data['username']);
   $u->password = $data['password'];
   $u->setEmail($data['email']);      
   $u->setFirstName($data['first_name']);
   $u->setLastName($data['last_name']);
   return $u;
}

i metodi get() e set() sono fatti in questo modo (sono tutti uguali quindi posto solo quello relativo al nome):
PHP:
public function getFirstName(){
   return $this->first_name;
}

public function setFirstName($firstName){
   $this->first_name = $firstName;
}

Quando devo inserire un nuovo utente nel database (cosa che non funziona) faccio in questo modo:
PHP:
public $user;
public $userRepository;

$this->userRepository = new UserRepository();
$db = Database::getInstance();

$this->user = new User();
$this->user->setUsername($username);
$this->user->setEmail($email);
$this->user->setPassword($password);
$this->user->save();

Dove save() si trova in User.php ed è:
PHP:
public function save() {
   $new = is_null($this->id);
   
   $db = Database::getInstance();
   
   if($new) {
      $sql = "INSERT INTO 'users' ('username', 'password', 'email', 'first_name', 'last_name') "
         . "VALUES (?, ?, ?, ?, ?)";
      $stmt = $db->prepare($sql);
      $stmt->execute(array($this->getUsername(), $this->password, $this->getEmail(), $this->getFirstName(), $this->getLastName()));
      $this->id = $db->lastInsertedId();
   }
   else {
      $sql = "UPDATE 'users' SET 'username' = ?, 'password' = ?, 'email' = ?, 'first_name' = ?, 'last_name' = ? WHERE 'id' = ?";
      $stmt = $db->prepare($sql);
      $stmt->execute(array($this->getUsername(), $this->password, $this->getEmail(), $this->getFirstName(), $this->getLastName(), $this->id));
   }
}

Quando invece faccio una modifica (anche questo non va) ad un utente presente nel database faccio così:
PHP:
public $user;
public $userRepository;
$this->userRepository = new UserRepository();
$this->user = $this->userRepository->findByUsername($username);
$db = Database::getInstance();
$this->user->setFirstName($first_name); 
$this->user->save();

Come mai queste due operazioni (INSERT e UPDATE) non vanno?
Grazie
 

stefano862

Nuovo Utente
5 Dic 2013
26
0
0
Risolto, era un errore stupidissimo. Nelle query di INSERT e UPDATE usavo le virgolette singole normali (') e non queste `... :D
 
Discussioni simili
Autore Titolo Forum Risposte Data
P [PHP] INSERT e UPDATE PHP 1
D [ASP] Mysql insert e update Classic ASP 2
S Insert into....on duplicate key update MySQL 2
C Aiuto INSERT INTO... ON DUPLICATE KEY UPDATE PHP 1
G problema con insert e update PHP 2
A Insert,Delete e Update file di testo PHP 0
P Access: recuperare Indice dopo un insert into MS Access 0
R INSERT INTO tabella non funziona Classic ASP 2
Z problemi con foreach insert into PHP 10
Y INSERT INTO PHP 0
M più insert tramite while loop PHP 1
A PROBLEMA: insert mysqli con dati Tagsinput Presentati al Forum 0
G Insert into select - Aiuto MySQL 0
L Insert php sql da una form multipla PHP 6
A [PHP] Problema query insert [RISOLTO] PHP 14
elpirata [RISOLTO][Mysql] Problema insert valori apostrofati MySQL 1
M [Javascript] Verifica calcolo prima di fare insert Javascript 13
Monital [PHP] Insert into non inserisce tutti i dati PHP 1
trattorino [PHP] problema entrata immagini insert PHP 1
C [Visual Basic] Errore INSERT su DB MySQL (VB.Net) Visual Basic 4
3_g errore con mysql insert in PDO PHP 29
Merlina3377 php insert dati su tabella sql PHP 9
T [PHP] impedire un doppio INSERT INTO dopo reload della pagina PHP 3
daniele8808 Insert a converted php array in a js object PHP 4
P [MySQL] Query su DB 1 e Insert su DB 2 PHP 11
Laskot Query al DB con php (INSERT) PHP 2
P [PHP] merge di 2 tabelle e insert su terza tabella PHP 15
giancadeejay [PHP] INSERT into tabella tramite scelta checkbox PHP 0
E [PHP] problema insert query PHP 9
O errore INSERT con oggeto datetime MySQL 2
A insert ed upload PHP 1
E Problemi auto increment con query Insert Into Select MySQL 2
A Insert multiple a partire da form html PHP 3
stellare21 insert con Sqlite e PHP PHP 4
Marco_88 Aiuto con istruzione INSERT Database 8
A Insert non inserirsce tutti i valori MySQL 11
MarcoGrazia [PDO] insert che non inserisce e non da errori PHP 1
MarcoGrazia Insert into che da errore: numero di parametri non validi.... MySQL 7
M Problemi con la insert PHP 1
I Insert con select da tabella e valori predefiniti MySQL 2
A Insert da ciclo for PHP 4
Monital [risolto] insert into if select non presente MySQL 7
G Inserimento loop in una INSERT query in PHP e MySQL PHP 2
H [RISOLTO]Problema connessione + insert mysqli PHP 10
L insert into da query select PHP 0
S Tempi per INSERT MySQL 7
A insert funziona in server locale ma non in remoto MySQL 7
Emix Problema Insert... PHP 10
M Sicurezza dati form per insert e select in database PHP 11
E Problema con INSERT INTO Classic ASP 2

Discussioni simili