====== Una possibile via pulita per iteragire con una tabella e PDO ====== Autore: **//Fabio Di Matteo//** \\ Ultima revisione: **// 12/07/2023 - 11:53 //** // // Ritorno un array con 2 chiavi. Una col codice di risposta (OK oppure ERR) e l'altra col messaggio d'errore oppure l'ultimo id inserito. function insertMovimento($descr,$person,$price) { global $DSN; if (!sbonText($descr)) { $res['status']='ERR'; $res['msg']='Errore: Caratteri non ammessi in descrizione!'; return $res; } if (!sbonText($person)) { $res['status']='ERR'; $res['msg']='Errore: Caratteri non ammessi in nel campo persona!'; return $res; } if (!sbonValuta($price)) { $res['status']='ERR'; $res['msg']='Errore: Caratteri non ammessi nel campo prezzo!'; return $res; } $date=date('Y-m-d'); try { $dsn= $DSN; $dbh = new PDO($dsn); $stmt = $dbh->prepare("insert into movimenti (id , descr, person, price, date) values (null, :DESCR, :PERSON , :PRICE, :DATE) ;" ); $stmt->bindParam(':DESCR', $descr, PDO::PARAM_STR); $stmt->bindParam(':PERSON', $person, PDO::PARAM_STR); $stmt->bindParam(':PRICE', $price); $stmt->bindParam(':DATE', $date, PDO::PARAM_STR); if ( $stmt->execute() ) { $res['status']='OK'; $res['lastid'] = $dbh->lastInsertId(); $dbh = null; return $res; }else{ $res['status']='ERR'; $res['msg']='Errore: errore nella query!'; return $res; } } catch (PDOException $e) { $res['status']='ERR'; $res['msg']='PDOException: '. $e->getMessage(); return $res; } } ===== Utilizzo ===== $e=insertMovimento($descr,$person,$price); if ($e['status']=='OK') { $lastInsertId=$e['lastid']; // ok }else{ $errore=$e['msg']; //errori }