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 [11.07.2015 23:22] – translated the introduction 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... ======
  
 All the examples in this area are carried out in the new style of WB 2.8.4. For older versions mostly you have to replace $oDb by $database, $oDb->TablePrefix by TABLE_PREFIX, and ->doQuery() by ->query() All the examples in this area are carried out in the new style of WB 2.8.4. For older versions mostly you have to replace $oDb by $database, $oDb->TablePrefix by TABLE_PREFIX, and ->doQuery() by ->query()
-===== SQL-Statements richtig aufgebaut ===== +===== Building SQL statements correctly ===== 
-Das ist schon <del>fast</del> ein ganzes Kapitel für sich. +This is  <del>almost</del> a whole chapter of its own. So the best thing to do first is to establish the most basic rules: 
-Also am besten erst ein mal die grundlegensten Regeln: +  * Statements must not be created in the argument parenthesis of a function / method. 
-  * Statements dürfen nicht in der Argumentenklammer einer Funktion/Methode erstellt werden. +  * Statements must always be set up in SQL-strict syntax 
-  * Statements müssen grundsätzlich im SQL-Strikt-Syntax aufgebaut werden +    * all SQL keywords must be written in capital letters. 
-    * alle SQL Schlüsselwörter müssen in Großbuchstaben geschrieben werden. +    * all field and table names must be enclosed in **`**Backticks**`**. 
-    * alle Feld- und Tabellennamen müssen in **`**Backticks**`** eingeschlossen werden. +  * Statements must not be limited to **"**text**"**, but only with **'**text**'**. If an  apostrophe **'** is needed within the string, this has to be masked with a backslash **\'**. 
-  * Statements dürfen nicht mit **”**text**”**, sondern ausschließlich mit **'**text**'** begrenzt werden. Wird innerhalb des Strings ein Apostroph **'** benötigt, so ist dieser mit einem Backslash **\'** zu maskieren. + 
-SQL-Statements sollten auch optisch so aufgebaut werden, dass sie problemlos und schnell gelesen und erfasst werden können. Die zeilenweise Aufteilung nach Action-Schlüsselwörtern ist an der Stelle sehr sinnvoll. Ist eine Zeile zu lang (Codingstandards) dann mit Einrückung auf mehrere Zeilen verteilen. Bei der Feldauswahl im SELECT-Bereich ist zu beachten, dass der Server komplette Datensätze (SELECT *) in der Regel deutlich schneller liefern kann, als eine lange Auswahlliste von einzelnen Feldern. +SQL statements should be built up visually such that they can be read and understood quickly and easily. The line by line breakdown by action keywords is very useful here. If a line is too long (Coding Standards) then spread with indentation on multiple lines. In the context of selecting fields it should be noted that the server can provide complete records (SELECT *)  significantly faster than a rule containing a long list of individual fields. To demonstrate the structure of statements, in the following there are some examples of the most important types of queries.
-Um den Aufbau von Statements zu demonstrieren, folgen einige Beispiele der wichtigsten Abfragetypen.+
 ---- ----
  
 ==== SELECT ==== ==== SELECT ====
-Alle vier Beispiele geben jeweils ein Result-Objekt mit allen Datensätzen der zum aktuellen Zeitpunkt sichtbaren Sections einer Seite zurück. +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 Beispiel-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_end` order by block, position");
 </code> </code>
-<code php Beispiel-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_start` AND `publ_end` ';
 $sql .= 'ORDER BY `block`, `position`'; $sql .= 'ORDER BY `block`, `position`';
 $oResult = $oDb->doQuery($sql); $oResult = $oDb->doQuery($sql);
 </code>  </code> 
-<code php Beispiel-3.php> +<code php Example-3.php> 
 $sql = 'SELECT `section_id`, `page_id`, `position`, `module`, ' $sql = 'SELECT `section_id`, `page_id`, `position`, `module`, '
      .        '`block`, `publ_start`, `publ_end` '      .        '`block`, `publ_start`, `publ_end` '
      . '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_start` AND `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>  </code> 
-<code php Beispiel-4.php> +<code php Example-4.php> 
 $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_start` AND `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>Zur Auflockerung eine kleine Quiz-Frage:\\ +</code>Let's have a short quiz now:\\ 
-Welche Beispiele lassen sich leichter lesen, verstehen und bei Bedarf auch leichter ändern? **1**&**2**  oder **3**&**4** ??+**Question:** Which of the examples are easier to read, understand and modify if required?\\ 
 +**Answers:** **1**&**2**  or **3**&**4** ??
 ---- ----
  
 ==== DELETE ==== ==== DELETE ====
-Bei dieser Abfrage kann man eigentlich nichts falsch machen...  ausser der Angabe falscher Lösch-Kriterien. ;-)\\ +With this query, you can not go wrong... except for the case that you provide the wrong deletion criteria. ;-)\\ 
-Aber auch hier gilt: Erst das Statement in einer Variablen aufbauen und diese dann an die Query-Methode übergeben.+But again: First build the statement and save it in a variable and then passe it to the query method.
 <code php DELETE-1.php> <code php DELETE-1.php>
 $sql = 'DELETE FROM `'.$oDb->TablePrefix.'users`' $sql = 'DELETE FROM `'.$oDb->TablePrefix.'users`'
      . 'WHERE `user_id`='.$iUserId;      . 'WHERE `user_id`='.$iUserId;
 $oDb->doQuery($sql); $oDb->doQuery($sql);
-</code>Datensätze sollten in der Regel nur über ihre Datensatz-ID gelöscht werden.+</code>Normally, records should be deleted only by specifying their record ID.
 ---- ----
  
 ==== INSERT / UPDATE ==== ==== INSERT / UPDATE ====
-In diesem Bereich wird es langsam interessant. Es gibt mehrere verschiedene Arten die Statements für INSERTs und UPDATEs aufzubauen. Speziell im Bereich der Werteübergabe.\\ +In this area it will get interesting. There 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 Regel, dass **allen** Feldern eines Datensatzes Werte zugewiesen werden müssen. Ausgenommen 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 applies, that values must be assigned to **all** record fields. Excluded are only the fields that are already defined in the table with a default value. Whenever data is to be written to the database, certain safety rules must be observed.
-Immer wenn Daten in die Datenbank geschrieben werden sollen, sind 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 correct) may **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 88: 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 94: 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 Änderbarkeit, der Umstand, dass auf die Reihenfolge der Felder keine Rücksicht genommen werden muss. Es genügt einfach, dass alle benötigten Felder vorhanden sind. Diese 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 changeability, is the fact that no consideration has to be made to the order of the fields. It is sufficient that simply all required fields are present. These 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 versucht, einen Datensatz einzufügen, der einen Index-Konflikt mit einem bestehende Datensatz auslöst, wird 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 set, the process will not be canceled, but the existing, old 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 funktioniert, sind 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 work, certain requirements must be met at the table.\\
 <code sql> <code sql>
 -- Structure of table  '{TABLE_PREFIX}settings' -- Structure of table  '{TABLE_PREFIX}settings'
Line 115: 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_key. Also, the structure of the statement differs from normal 'SET' - standard, in turn, several records can be changed in one run:
-Auch der Aufbau des Statements weicht vom normalen 'SET' - Standard ab, dafü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 126: Line 121:
     }</code>     }</code>
  
-  
en/dev/all/examples/sql.1436656920.txt.gz · Last modified: 11.07.2015 23:22 by mrbaseman