1
+ <?php
2
+ /*
3
+ * This class will run queries on master/slave servers depending on the query itself.
4
+ */
5
+ class mysqlims extends mysqli
6
+ {
7
+ private $ mysqliW ;
8
+ private $ mysqliR = null ;
9
+
10
+ /*
11
+ * Pass main and slave connection arrays to the constructor, and strict as true/false
12
+ *
13
+ * @param array $main
14
+ * @param array $slave
15
+ * @param boolean $strict
16
+ *
17
+ * @return void
18
+ */
19
+ public function __construct ($ main , $ slave = false , $ strict = false )
20
+ {
21
+ var_dump ($ main );
22
+ var_dump ($ slave );
23
+ if ($ strict ) {
24
+ $ this ->mysqliW = new mysqli_strict ($ main ['host ' ],
25
+ $ main ['user ' ], $ main ['pass ' ],
26
+ $ main ['name ' ], $ main ['port ' ]);
27
+ if ($ slave && is_array ($ slave ) && isset ($ slave ['enabled ' ]) && $ slave ['enabled ' ]
28
+ === true ) {
29
+ $ this ->mysqliR = new mysqli_strict ($ slave ['host ' ],
30
+ $ slave ['user ' ], $ slave ['pass ' ],
31
+ $ slave ['name ' ], $ slave ['port ' ]);
32
+ }
33
+ } else {
34
+ $ this ->mysqliW = new mysqli ($ main ['host ' ],
35
+ $ main ['user ' ], $ main ['pass ' ],
36
+ $ main ['name ' ], $ main ['port ' ]);
37
+ if ($ slave && is_array ($ slave ) && isset ($ slave ['enabled ' ]) && $ slave ['enabled ' ]
38
+ === true ) {
39
+ $ this ->mysqliR = new mysqli ($ slave ['host ' ],
40
+ $ slave ['user ' ], $ slave ['pass ' ],
41
+ $ slave ['name ' ], $ slave ['port ' ]);
42
+ }
43
+ }
44
+
45
+ if ($ this ->mysqliW ->connect_errno ) {
46
+ throw new Exception ("Failed to connect to MySQL: ( " .$ this ->mysqliW ->connect_errno .") " .$ this ->mysqliW ->connect_error );
47
+ }
48
+
49
+ if ($ this ->mysqliR ->connect_errno ) {
50
+ throw new Exception ("Failed to connect to MySQL: ( " .$ this ->mysqliR ->connect_errno .") " .$ this ->mysqliR ->connect_error );
51
+ }
52
+ }
53
+
54
+ /*
55
+ * Override standard mysqli_prepare to select master/slave server
56
+ * @param $string query
57
+ *
58
+ * @return mysqli_stmt
59
+ */
60
+ public function prepare ($ query )
61
+ {
62
+ if (stripos ($ query , "SELECT " ) && stripos ($ query , "FOR UPDATE " ) === false && $ this ->mysqliR !== null ) {
63
+ return $ this ->mysqliR ->prepare ($ query );
64
+ } else {
65
+ return $ this ->mysqliW ->prepare ($ query );
66
+ }
67
+ }
68
+
69
+ /*
70
+ * Override standard mysqli_query to select master/slave server
71
+ * @param string $query
72
+ * @param int $resultmode
73
+ *
74
+ * @return boolean
75
+ * @return mixed
76
+ */
77
+ public function query ($ query , $ resultmode = MYSQLI_STORE_RESULT )
78
+ {
79
+ if (stripos ($ query , "SELECT " ) && stripos ($ query , "FOR UPDATE " ) === false && $ this ->mysqliR !== null ) {/* Use readonly server */
80
+ return $ this ->mysqliR ->query ($ query , $ resultmode );
81
+ } else {
82
+ return $ this ->mysqliW ->query ($ query , $ resultmode );
83
+ }
84
+ }
85
+ }
0 commit comments