@@ -20,11 +20,7 @@ class DB
2020 private \PDO $ pdo ;
2121 private string $ _action ="" ;
2222 private int $ _count ;
23- private array $ option =[
24- \PDO ::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8 " ,
25- \PDO ::ATTR_EMULATE_PREPARES =>false ,
26- \PDO ::ATTR_ERRMODE =>\PDO ::ERRMODE_EXCEPTION
27- ] ;
23+ private string $ db_name ;
2824 use BuildQuery;
2925 private function __construct (string $ host ="" ,string $ db_name ="" ,string $ user_name ="" ,string $ password ="" )
3026 {
@@ -33,8 +29,13 @@ private function __construct(string $host="",string $db_name="",string $user_nam
3329 $ this ->_error = null ;
3430 $ this ->_lastID = -1 ;
3531 $ this ->_count = 0 ;
32+ $ this ->db_name = $ db_name ;
3633 //
37- $ this ->pdo = new \PDO ("mysql:host= " . $ host . ";dbname= " . $ db_name .";charset=utf8mb4 " , $ user_name ,$ password ,$ this ->option );
34+ $ this ->pdo = new \PDO ("mysql:host= " . $ host . ";dbname= " . $ db_name .";charset=utf8mb4 " , $ user_name ,$ password );
35+ $ this ->pdo ->setAttribute (\PDO ::MYSQL_ATTR_INIT_COMMAND ,'SET NAMES utf8 ' );
36+ $ this ->pdo ->setAttribute (\PDO ::ATTR_EMULATE_PREPARES ,false );
37+ $ this ->pdo ->setAttribute (\PDO ::ATTR_PERSISTENT ,true );
38+ $ this ->pdo ->setAttribute (\PDO ::ATTR_ERRMODE ,\PDO ::ERRMODE_EXCEPTION );
3839 } catch (\PDOException $ ex ) {
3940 echo $ ex ->getMessage ();
4041 die ();
@@ -181,4 +182,31 @@ function rowCount(){
181182 }
182183 return $ this ->_count ;
183184 }
185+
186+ function beginTransaction (): bool
187+ {
188+ return $ this ->pdo ->beginTransaction ();
189+ }
190+ function commit (){
191+ return $ this ->pdo ->commit ();
192+ }
193+ function rollBack (){
194+ return $ this ->pdo ->rollBack ();
195+ }
196+
197+ /**
198+ * @throws Exception
199+ */
200+ function transaction (\Closure $ callable ){
201+ try {
202+ $ this ->pdo ->beginTransaction ();
203+ $ callable ($ this );
204+ $ this ->pdo ->commit ();
205+ }catch (\Exception $ ex ){
206+ if ($ this ->pdo ->inTransaction ()) {
207+ $ this ->pdo ->rollBack ();
208+ }
209+ throw $ ex ;
210+ }
211+ }
184212}
0 commit comments