Bonjour, j'ai trouvais un code pour mettre à jour une base de données distante à partir d'une base de données locale et j'aimerai bien avoir votre avis
Merci
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
 <?php
 
session_start();
 
/* ----------------------------
 deconnection demandée
   ---------------------------- */
if ($func=='deconnect'){
    unset($_SESSION['host']);
    unset($_SESSION['base']);
    unset($_SESSION['user']);
    unset($_SESSION['pass']);
    // redirection vers la page de login
    header('Location:'.basename($PHP_SELF));
    exit();
}
 
// get params from connection
$_SESSION['host']=(isset($_POST['host'])) ? $_POST['host'] : $_SESSION['host'] ;
$_SESSION['base']=(isset($_POST['base'])) ? $_POST['base'] : $_SESSION['base'] ;
$_SESSION['user']=(isset($_POST['user'])) ? $_POST['user'] : $_SESSION['user'] ;
$_SESSION['pass']=(isset($_POST['pass'])) ? $_POST['pass'] : $_SESSION['pass'] ;
 
/* ----------------------------
  Begining : connection to the database
   ---------------------------- */
if (!@mysql_connect($_SESSION['host'],$_SESSION['user'],$_SESSION['pass']) || $_SESSION['base']=="") {
    if ($func=='connect') {echo $_SESSION['user'],':',eregi_replace('[^A-Za-z0-9 ]','*',$_SESSION['pass']),'@',$_SESSION['host'];}
    @mysql_close();
    die( '
<table>
<form method="post" name="db_table_form" action="'.$_SERVER['PHP_SELF'].'">
<input type="hidden" name="func" value="connect" />
<tr><td>Serveur demand&eacute;</td>
    <td><input name="host" type="text" value="'.$_SESSION['host'].'" /></td></tr>
<tr><td>Base demand&eacute;e</td>
    <td><input type="text" name="base" value="'.$_SESSION['base'].'"  /></td></tr>
<tr><td>Login MySQL</td>
    <td> <input type="text" name="user" value="'.$_SESSION['user'].'" /></tr>
<tr><td>Password MySQL</td>
    <td><input type="password" name="pass" value="'.$_SESSION['pass'].'" /></td></tr>
<tr><td></td>
    <td><input type="submit" value="connection" /></td></tr>
</form>
</table>');
}
 
if (!mysql_select_db($_SESSION['base'])) {
    @mysql_close();
    die ('
<a href="'.$_SERVER['PHP_SELF'].'?func=deconnect">Déconnecter</a><br />
<font color="red">La base '.$_SESSION['base'].' ne semble pas exister.<br />
'.$_SESSION['host'].'<br />
'.$_SESSION['base'].'<br />
'.$_SESSION['user']);
}
/* ----------------------------
  Second : choose the tables
   ---------------------------- */
    if (!isset($table_to_dump)) {
        if (@file_exists(_SVG_INI_FILE)){
            $ini_array = parse_ini_file(_SVG_INI_FILE,true);
            $jav='';$virgule='';$i=0;
            foreach($ini_array as $name => $table){
                if (sizeof($table>0)){
                    $list_names_ini.='<option value="'.$i.'">'.base64_decode($name).'</option>'."\n";
                    $jav.=$virgule.'Array(';
                    $virgule_fe='';
                    foreach($table as $table_name){
                        $jav.=$virgule_fe.'"'.$table_name.'"';
                        $virgule_fe=', ';
                    }
                    $jav.=')';
                    $virgule=', ';
                    $i++;
                }
            }
/*        dbg( $ini_array );
        echo $jav.'<br />';
        echo $list_names_ini.'<br />';
        dbg( $ini_array );*/
        }
 
        $result = mysql_query('show tables;');
        echo '
<a href="'.$_SERVER['PHP_SELF'].'?func=deconnect">Déconnecter</a><br />
<form method="post" name="db_table_form" action="'.$_SERVER['PHP_SELF'].'">
    <input type="hidden" name="tables" value="ok" />
    <input type="hidden" id="structure_svg" name="structure_svg" value="" />
    <fieldset style="width:300px;">
    <legend>Configs</legend>
    Saved config : <br />
    <select id="choix_tables" name="choix_tables" onchange="load_structure(this.value);">
        <option value="">Tous décocher</option>
        <option value="all">Tous cocher</option>
        '.$list_names_ini.'
    </select>
    <input type="submit" value="ok" /><input type="button" value="Del" onClick="confirm_del();"><br />
    ou créer une nouvelle :<br />
    <input type="text" name="to_save" /><br />
    </fieldset>
    <br />
    Choisir les tables dont vous voulez faire la sauvegarde :<br />';
        $virgule='';
        while(list($tables)=mysql_fetch_array($result)){
            $id=str_replace('=','',base64_encode($tables));
            echo '<input type="checkbox" id="'.$id.'" name="table_to_dump[]" value="'.$tables.'" />'.$tables.'<br />'."\n";
            $jav_all.=$virgule.'"'.$id.'"';
            $virgule=', ';
        }
        mysql_close();
        die('
<input type="submit" value="Lancer sauvegarde" />
</form>
<script type="text/javascript">
    // js should work with firefox / IE
    tab_uncheck=Array('.$jav_all.');
    tab_to_check=Array('.$jav.');
    function load_structure(value){
        if (value=="all") {checkedornot=\'checked="checked"\'; value=""}
        else              {checkedornot=\'\';}

        for (i = 0; i < tab_uncheck.length; i++) {
            document.getElementById(tab_uncheck[i]).checked=checkedornot;
        }
        document.getElementById("structure_svg").value==\'\';
        if (value=="") {return;}
        tab_temp=Array();
        tab_temp=tab_to_check[value];
        for (i = 0; i < tab_temp.length; i++) {
            document.getElementById(tab_temp[i]).checked=\'checked="checked"\';
        }
        value++;
        texte=document.getElementById("choix_tables").options[value+1].text;
        document.getElementById("structure_svg").value=texte;
    }
    function confirm_del(){
        temp=document.getElementById("choix_tables");
        index=temp.selectedIndex;
        if (temp.value!=""
         && temp.value!="all"
         && confirm("Confirmer la suppression de "+temp[index].text+" ?") ) {
            document.db_table_form.tables.value=temp[index].value;
            document.db_table_form.submit();
        }
    }
</script>');
 
/* ----------------------------
   Then save the selected tables
    Or delete a config
   ---------------------------- */
 
    } else {
        // <detruire une config>
        if ($_POST['tables']!='ok'){
            $ini_array = parse_ini_file(_SVG_INI_FILE,true);
            $i=0;
            foreach ($ini_array as $key => $value) {
                if ($i==$_POST['choix_tables']){ unset($ini_array[$key]); }
                $i++;
            }
            if (sizeof($ini_array)>0){
                array2ini_file ($ini_array, _SVG_INI_FILE);
            } else {
                unlink(_SVG_INI_FILE);
            }
            header('Location:'.basename($PHP_SELF));
            exit();
        }
        // </detruire une config>
 
        // <maybe save to new config>
        if (!empty($_POST['to_save'])){
            $_array=array();
        }
        // </maybe save to new config>
 
        // recupere le fichier à créer
        $file_nametxt=$_SESSION['base']."_".date("Y_m_d").$_POST['structure_svg'].".sql";
        if (file_exists($file_nametxt))unlink($file_nametxt);
        $file_handle=fopen($file_nametxt,"a");
 
        foreach($table_to_dump as $table){
            // <maybe save to new config>
            if (!empty($_POST['to_save'])){
                $_array[]=str_replace('=','',base64_encode($table));
            }
            // </maybe save to new config>
 
            // <get the create table>
            list($inutile,$creation)= mysql_fetch_array(mysql_query('SHOW CREATE TABLE '.$table.';'));
            $entete = "\n".'DROP TABLE IF EXISTS `'.$table.'`;'."\n";
            $entete.= $creation.';';
            fputs($file_handle, $entete."\n");
            // </get the create table>
 
            $query = 'SELECT * FROM '.$table.';';    // recupre les elements de la table
            $datacreate = mysql_query($query);
            if (mysql_num_rows($datacreate) > 0) {    // si la table n'est pas vide
                fputs($file_handle, 'LOCK TABLES '.$table.' WRITE;'."\n");
                // <prepare la création de la table>
                $insert = 'INSERT INTO `'.$table.'` values ';
                // </ prepare la création de la table>
 
                $nb=0; $virgule='';
                // <insertion des données>
                while($ligne = mysql_fetch_assoc($datacreate))    {
                    $ligne = array_map('separe', $ligne);            // 
                    $data_new = implode(',',$ligne);                // tableau -> chaine unique                
                    $data .= $virgule.'('.$data_new.')';
                    $virgule=', ';
                    if ($nb ==_NB_LIMIT){                             // Nouvelle ligne
                        fputs($file_handle, $insert.' '.$data.';'."\n");
                        $data='';
                        $nb=0; $virgule='';
                    }
                    $nb++;
                }
                // </ insertion des données>
 
                switch ($nb){
                    case '0': $data=$insert; break;
                    default : $virgule=', ';
                }
                if ($data!='' && $nb<_NB_LIMIT && $nb!=0){
                    fputs($file_handle, $insert.' '.$data.';'."\n");
                }
                $nb=0; $virgule=''; $data='';
            }
            fputs($file_handle, 'UNLOCK TABLES;'."\n\n");
        }
        // < maybe save to new config>
        if (!empty($_POST['to_save'])){
            $ini_array=array();
            if (@file_exists(_SVG_INI_FILE)){
                $ini_array = parse_ini_file(_SVG_INI_FILE,true);
            }
            $ini_array[str_replace('=','',base64_encode($_POST['to_save']))]=$_array;
/*    dbg( $_array);
    dbg($ini_array);*/
            array2ini_file ($ini_array, _SVG_INI_FILE);
        }
        // < /maybe save to new config>
    }
    @mysql_close();
    fclose($file_handle);
 
    // force upload the file
    DEFINE('FICHIER',($file_nametxt));
    $NomFichier=basename($file_nametxt);
    $taille=filesize($file_nametxt);
    header("Content-Type: application/force-download; name=\"$file_nametxt\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: $taille");
    header("Content-Disposition: attachment; filename=\"$file_nametxt\"");
    header("Expires: 0");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    readfile($file_nametxt);
    unlink($file_nametxt);
    header('location:'.$PHP_SELF);
    exit();
 
 
    function separe($tbl) // utilisee dans array_map dans backup pour formater la recup du query
    {
        $tbl=mysql_escape_string($tbl);     // prepare les données pour etre injectées dans mysql
        if(is_numeric($tbl)){ return $tbl;}    // si chiffre , c'est bon
        if(!$tbl){return "NULL";}            // si c'est null on le dit
        return "'".$tbl."'";                
    }
 
    function array2ini_file($array, $file) 
    //opération inverse de "$array = parse_ini_file($file, TRUE);" 
    { 
      $fp = fopen($file,"w") 
        or die("<b>Erreur - Un fichier de configuration n'a pas pu être crée !</b>"); 
      fwrite($fp, ";fichier automatique - ".basename($file)."\n"); 
      while(list($key, $value) = each($array)) 
      { 
        fwrite ($fp, "\n[".$key."]\n"); 
        while(list($k, $v) = each($value)) 
          fwrite($fp, $k." = ".$v."\n"); 
      } 
      return(TRUE); 
    } 
 
    // debugging function 
    function dbg($value){
        echo '<pre>';
        var_dump($value);
        echo '</pre>';
    }
 
?>
Merci