User Tools

Site Tools


en:dev:all:examples:sql

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
en:dev:all:examples:sql [16.07.2015 21:28] – [DELETE] translated mrbasemanen:dev:all:examples:sql [20.02.2019 07:49] (current) – [SELECT] Manuela v.d.Decken
Line 1: Line 1:
-FIXME **This page is not fully translated, yet. Please help completing the translation.**\\ //(remove this paragraph once the translation is finished)// 
- 
 ====== This is how SQL works... ====== ====== This is how SQL works... ======
  
Line 18: Line 16:
 Each of all the four examples give back a result-object with all records of the visible sections of a page at the current time. Each of all the four examples give back a result-object with all records of the visible sections of a page at the current time.
 <code php Example-1.php>  <code php Example-1.php> 
-$oResult = $oDb->doQuery("SELECT section_id, page_id, position, module, block, publ_start, publ_end FROM ".TABLE_PREFIX."sections where page_id= $iPageId and (publ_start = 0 OR publ_start <= $iTimestamp and (publ_end = 0 OR publ_end >= $iTimestamp ) order by block, position");+$oResult = $oDb->doQuery("SELECT section_id, page_id, position, module, block, publ_start, publ_end FROM ".TABLE_PREFIX."sections where page_id= $iPageId and $iTimestamp between `publ_start` and `publ_endorder by block, position");
 </code> </code>
 <code php Example-2.php>  <code php Example-2.php> 
 $sql  = 'SELECT `section_id`, `page_id`, `position`, `module`, `block`, `publ_start`, `publ_end` FROM `'.$oDb->TablePrefix.'sections` '; $sql  = 'SELECT `section_id`, `page_id`, `position`, `module`, `block`, `publ_start`, `publ_end` FROM `'.$oDb->TablePrefix.'sections` ';
-$sql .= 'WHERE `page_id`='.$iPageId.' AND (`publ_start`=0 OR `publ_start`<='.$iTimestamp.') AND (`publ_end`=0 OR `publ_end`>='.$iTimestamp.'';+$sql .= 'WHERE `page_id`='.$iPageId.' AND '.$iTimestamp.' BETWEEN `publ_startAND `publ_end` ';
 $sql .= 'ORDER BY `block`, `position`'; $sql .= 'ORDER BY `block`, `position`';
 $oResult = $oDb->doQuery($sql); $oResult = $oDb->doQuery($sql);
Line 31: Line 29:
      . 'FROM `'.$oDb->TablePrefix.'sections` '      . 'FROM `'.$oDb->TablePrefix.'sections` '
      . 'WHERE `page_id`='.$iPageId.' '      . 'WHERE `page_id`='.$iPageId.' '
-            'AND (`publ_start`=0 OR `publ_start`<='.$iTimestamp.') ' +            'AND '.$iTimestamp.' BETWEEN `publ_startAND `publ_end` '
-            'AND (`publ_end`=0 OR `publ_end`>='.$iTimestamp.''+
      . 'ORDER BY `block`, `position`';      . 'ORDER BY `block`, `position`';
 $oResult = $oDb->doQuery($sql);      $oResult = $oDb->doQuery($sql);     
Line 39: Line 36:
 $sql = 'SELECT * FROM `'.$oDb->TablePrefix.'sections` ' $sql = 'SELECT * FROM `'.$oDb->TablePrefix.'sections` '
      . 'WHERE `page_id`='.$iPageId.' '      . 'WHERE `page_id`='.$iPageId.' '
-            'AND (`publ_start`=0 OR `publ_start`<='.$iTimestamp.') ' +            'AND '.$iTimestamp.' BETWEEN `publ_startAND `publ_end` '
-            'AND (`publ_end`=0 OR `publ_end`>='.$iTimestamp.''+
      . 'ORDER BY `block`, `position`';      . 'ORDER BY `block`, `position`';
 $oResult = $oDb->doQuery($sql);      $oResult = $oDb->doQuery($sql);     
 </code>Let's have a short quiz now:\\ </code>Let's have a short quiz now:\\
-Question: Which of the examples are easier to read, to understand and to modify if required? **1**&**2**  or **3**&**4** ??+**Question:** Which of the examples are easier to read, understand and modify if required?\\ 
 +**Answers:** **1**&**2**  or **3**&**4** ??
 ---- ----
  
Line 58: Line 55:
  
 ==== INSERT / UPDATE ==== ==== INSERT / UPDATE ====
-In diesem Bereich wird es langsam interessantEs gibt mehrere verschiedene Arten die Statements für INSERTs und UPDATEs aufzubauenSpeziell im Bereich der Werteübergabe.\\ +In this area it will get interestingThere are several different ways to build the statements for INSERTs and UPDATEs. Especially in the field of supplying the values.\\ 
-Bei **allen** Arten von INSERTs gilt jedoch die SQL-Strikt Regeldass **allen** Feldern eines Datensatzes Werte zugewiesen werden müssenAusgenommen hiervon sind nur die Felder, die in der Tabelle bereits mit einem Default-Wert vordefiniert sind. +With **all** kinds of INSERTs, however the SQL-strict rule appliesthat values must be assigned to **all** record fieldsExcluded are only the fields that are already defined in the table with a default valueWhenever data is to be written to the databasecertain safety rules must be observed.
-Immer wenn Daten in die Datenbank geschrieben werden sollensind bestimmte Sicherheitsregeln zu beachten. +
-  * Es muss sichergestellt sein, dass nur der richtige Datentyp übergeben wird. +
-  * Es muss sichergestellt sein, dass jeder übergebene Wert zuvor überprüft wurde und gültig ist. +
-  * Es dürfen nicht Werte aus Superglobalen Arrays, speziell aus //$_POST/$_GET/$_REQUEST///usw. direkt übergeben werden. +
-  * Stringvariable müssen vor der Übergabe '//escaped//' werden. Dazu ist ausschließlich die Methode //escapeString()// des Datenbankobjektes zu verwenden, da nur diese Methode genau so maskiert, wie es die aktuell benutzte Datenbank benötigt. Irgendwelche andere Methoden wie //addslashes()// oder selbstgebaute Funktionen etc. sind **nicht** zulässig. +
-  * Enthält eine Tabelle ein //Autoincrement//-Feld, so darf dieses bei einem INSERT **nicht** gesetzt und bei einem UPDATE **nicht** verändert werden. Bei einer unter STRIKT laufenden Datenbank würde dies einen schweren Fehler auslösen und das Programm abbrechen. Ebenso wird ein Abbruch ausgelöst, wenn einem Feld ohne Default-Wert bei einem INSERT kein Wert zugewiesen wird. +
-:!: Im Umfeld von WebsiteBaker ist für INSERT und UPDATE Statements ausschließlich die '**SET**'-Methode zur Werteübergabe zulässig!+
  
-Erst ein Beispiel wie ein Statement (obwohl syntaktisch richtig) **nicht** aussehen darf:+  * It must be ensured that only the correct data type is passed. 
 +  * It must be ensured that any value passed was previously examined and is valid. 
 +  * It is not allowed to pass values of superglobal arrays, especially from //$_POST/$_GET/$_REQUEST///etc. directly. 
 +  * String variables have to be '//escaped//' before the handover. For this purpose only the //escapeString()// method of the database object may be used, because only this method is able to mask exactly how it is required by the database currently in use. Any other methods like //addslashes()// or home-built functions etc. are **not** allowed. 
 +  * If a table contains an //autoincrement//-field, that one may **not** be set by an INSERT and **not** be changed by an UPDATE. In a database running in strict mode this would trigger a severe error and cause the program to exit immediately. Likewise, an abort is triggered when no value is assigned to a field with no default value, when an INSERT is performed. 
 + 
 +:!: In the context of WebsiteBaker  for INSERT and UPDATE statements the only permitted method is the '**SET**'-method for supplying values. 
 + 
 +Only one example of how such a statement (although syntactically correctmay **not** look like:
 <code php insert-01.php> <code php insert-01.php>
-// das ist übrigens ein Original-Statement aus WB-2.8.3-SP1 'add user'+// by the way this is an original statement from WB-2.8.3-SP1 'add user'
 $sql = "INSERT INTO ".TABLE_PREFIX."users (group_id,groups_id,active,username,password,display_name,home_folder,email,timezone, language) VALUES ('$group_id', '$groups_id', '$active', '$username','$md5_password','$display_name','$home_folder','$email','-72000', '$default_language')"; $sql = "INSERT INTO ".TABLE_PREFIX."users (group_id,groups_id,active,username,password,display_name,home_folder,email,timezone, language) VALUES ('$group_id', '$groups_id', '$active', '$username','$md5_password','$display_name','$home_folder','$email','-72000', '$default_language')";
 </code> </code>
-Das selbe Statement jetzt nach den zuvor beschriebenen Regeln:+The same statement now following the rules described above:
 <code php insert-02.php> <code php insert-02.php>
 $sql = 'INSERT INTO `'.$oDb->TablePrefix.'users` ' $sql = 'INSERT INTO `'.$oDb->TablePrefix.'users` '
Line 87: Line 85:
          '`language`=\''.$oDb->escapeString($default_language).'\'';          '`language`=\''.$oDb->escapeString($default_language).'\'';
 </code> </code>
-Ein UPDATE sieht im Prinzip genau so aus:+An UPDATE basically looks like this:
 <code php SET-1.php> <code php SET-1.php>
 $sql = 'UPDATE `'.$oDb->TablePrefix.'users` ' $sql = 'UPDATE `'.$oDb->TablePrefix.'users` '
Line 93: Line 91:
          '`active`=1 '          '`active`=1 '
      . 'WHERE `user_id`='.$iUserId;      . 'WHERE `user_id`='.$iUserId;
-</code>Ein großer Vorteil der SET-Methode ist neben der Übersichtlichkeit und der leichten Änderbarkeitder Umstand, dass auf die Reihenfolge der Felder keine Rücksicht genommen werden mussEs genügt einfach, dass alle benötigten Felder vorhanden sindDiese Vorteile wiegen weit stärker als die dafür zusätzlich benötigte Zahl an Zeilen.+</code>A major advantage of SET-method in addition to the clarity and ease of changeabilityis the fact that no consideration has to be made to the order of the fieldsIt is sufficient that simply all required fields are presentThese benefits by far outweigh the fact that a few more lines of code are needed.
 ---- ----
- 
  
 ==== REPLACE ==== ==== REPLACE ====
-//(mySQL spezifische Erweiterung zu ANSI-SQL)//+//(MySQL specific extension to ANSI SQL)//
  
-Wie überall gibt es fast keine Regel ohne Ausnahme.\\ +Like everywhere else, there is almost no rule without exception.\\ 
-**REPLACE** funktioniert primär identisch wie **INSERT**. Mit einem kleinen, jedoch entscheidenden Unterschied:\\ +**REPLACE** works primarily the same as **INSERT**. With a small but crucial difference:\\ 
-Wird versuchteinen Datensatz einzufügender einen Index-Konflikt mit einem bestehende Datensatz auslöstwird der Prozess nicht abgebrochen, sondern der bestehende, alte Datensatz wird gelöscht und der neue eingefügt.\\ +If you try to insert a record which would cause an index conflict with an existing data setthe process will not be canceledbut the existingold record is deleted and the new values are added instead.\\ 
-**REPLACE** ist grundsätzlich nicht für Tabellen geeignet, die einen Autoincrement-Wert nutzen, der in einer anderen Tabelle als Fremdschlüssel benutzt wird.\\ +**REPLACE** is fundamentally unsuitable for tables that use an autoincrement value that is used in another table as a foreign key.\\ 
-Der WebsiteBaker-Core benutzt dieses SQL-Kommando z.B. zum Eintragen und Ändern von Werten in die Tabelle `settings`. Damit das Ganze funktioniertsind gewisse Anforderungen an die Tabelle zu erfüllen.\\+The WebsiteBaker core uses this SQL command, for example, for entering and changing values in the table `settings`. For this to workcertain requirements must be met at the table.\\
 <code sql> <code sql>
 -- Structure of table  '{TABLE_PREFIX}settings' -- Structure of table  '{TABLE_PREFIX}settings'
Line 114: Line 111:
 ){TABLE_ENGINE}; ){TABLE_ENGINE};
 </code> </code>
-Im Statement muss zwingend ein Wert für das Feld mit dem PRIMARY_KEY oder UNIQUE_KEY übergeben werden. +In a statement it is mandatory to pass a value for the field with the PRIMARY_KEY or unique_keyAlso, the structure of the statement differs from normal 'SET'standard, in turnseveral records can be changed in one run:
-Auch der Aufbau des Statements weicht vom normalen 'SET'Standard abdafür können als Ausgleich auch mehrere Datensäte in einem Zug geändert werden:+
 <code php snippet.php> <code php snippet.php>
     $sql = 'REPLACE INTO `'.$oDb->TablePrefix.'settings` (`name`, `value`) '     $sql = 'REPLACE INTO `'.$oDb->TablePrefix.'settings` (`name`, `value`) '
Line 125: Line 121:
     }</code>     }</code>
  
-  
en/dev/all/examples/sql.1437082137.txt.gz · Last modified: 16.07.2015 21:28 by mrbaseman