v5:userguide:portable_sql
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
reference:portable_sql [2015/12/04 18:02] – mnewnham | v5:reference:portable_sql [2016/01/13 02:31] – ↷ Links adapted because of a move operation mnewnham | ||
---|---|---|---|
Line 26: | Line 26: | ||
^Oracle|select * from (select * from table) where rownum <= 10| | ^Oracle|select * from (select * from table) where rownum <= 10| | ||
- | This feature of getting a subset of data is so useful that in the PHP class library ADOdb, we have a [[reference: | + | This feature of getting a subset of data is so useful that in the PHP class library ADOdb, we have a [[v5:reference:selectlimit]] function that allows you to hide the implementation details within a function that will rewrite your SQL for you: |
<code php> | <code php> | ||
Line 34: | Line 34: | ||
==== Fetch Modes Within Select Statements ==== | ==== Fetch Modes Within Select Statements ==== | ||
- | PHP allows you to retrieve database records as arrays. You can choose to have the arrays indexed by field name or number. However different low-level PHP database drivers are inconsistent in their indexing efforts. ADOdb allows you to determine your prefered mode. You set this by setting the variable [[reference: | + | PHP allows you to retrieve database records as arrays. You can choose to have the arrays indexed by field name or number. However different low-level PHP database drivers are inconsistent in their indexing efforts. ADOdb allows you to determine your prefered mode. You set this by setting the variable [[v5:reference:adodb_fetch_mode]] to either of the constants: |
* ADODB_FETCH_NUM (for numeric indexes) | * ADODB_FETCH_NUM (for numeric indexes) | ||
* ADODB_FETCH_ASSOC (using field names as an associative index). | * ADODB_FETCH_ASSOC (using field names as an associative index). | ||
Line 44: | Line 44: | ||
Another problem with SELECTs is that some databases do not return the number of rows retrieved from a select statement. This is because the highest performance databases will return records to you even before the last record has been found. | Another problem with SELECTs is that some databases do not return the number of rows retrieved from a select statement. This is because the highest performance databases will return records to you even before the last record has been found. | ||
- | In ADOdb, [[reference: | + | In ADOdb, [[v5:reference:recordcount]] returns the number of rows returned, or will emulate it by buffering the rows and returning the count after all rows have been returned. This can be disabled for performance reasons when retrieving large recordsets by setting the global variable [[v5:reference:adodb_countrecs]] = false. This variable is checked every time a query is executed, so you can selectively choose which recordsets to count. |
- | If you prefer to set '' | + | If you prefer to set '' |
<code php> | <code php> | ||
Line 100: | Line 100: | ||
When you create records, you need to generate unique id's for each record. There are two common techniques: (1) auto-incrementing columns and (2) sequences. | When you create records, you need to generate unique id's for each record. There are two common techniques: (1) auto-incrementing columns and (2) sequences. | ||
- | Auto-incrementing columns are not supported by some databases, so for portability, | + | Auto-incrementing columns are not supported by some databases, so for portability, |
<code php> | <code php> | ||
Line 134: | Line 134: | ||
ADOdb provides the following functions for portably generating SQL functions as strings to be merged into your SQL statements. | ADOdb provides the following functions for portably generating SQL functions as strings to be merged into your SQL statements. | ||
- | Function Description | + | ^Function^Description^ |
- | DBDate($date) Pass in a UNIX timestamp or ISO date and it will convert it to a date string formatted for INSERT/ | + | ^DBDate($date)|Pass in a UNIX timestamp or ISO date and it will convert it to a date string formatted for INSERT/ |
- | DBTimeStamp($date) Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp string formatted for INSERT/ | + | ^DBTimeStamp($date)|Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp string formatted for INSERT/ |
- | SQLDate($date, | + | ^SQLDate($date, |
- | OffsetDate($date, | + | ^OffsetDate($date, |
- | Concat($s1, $s2, ...) Portably concatenate strings. Alternatively, | + | ^Concat($s1, $s2, ...)|Portably concatenate strings. Alternatively, |
- | IfNull($fld, | + | ^IfNull($fld, |
- | Param($name) Generates bind placeholders, | + | ^Param($name)|Generates bind placeholders, |
- | $db-> | + | ^$db-> |
- | $db-> | + | ^$db-> |
- | $db-> | + | ^$db-> |
- | $db-> | + | ^$db-> |
- | $db-> | + | ^$db-> |
- | $db-> | + | ^$db-> |
- | $db-> | + | ^$db-> |
- | DDL and Tuning | + | ===== DDL and Tuning |
- | There are database design tools such as ERWin or Dezign that allow you to generate data definition language commands such as ALTER TABLE or CREATE INDEX from Entity-Relationship diagrams. | + | There are database design tools such as ERWin or Dezign that allow you to generate data definition language commands such as '' |
- | However if you prefer to use a PHP-based table creation scheme, | + | However if you prefer to use a PHP-based table creation scheme, |
- | Auto-increment primary key ' | + | |
- | The person' | + | The person' |
- | The date and time of record creation ' | + | The date and time of record creation ' |
- | The person' | + | The person' |
- | Also create a compound index consisting of ' | + | Also create a compound index consisting of ' |
+ | <code php> | ||
$datadict = NewDataDictionary($connection); | $datadict = NewDataDictionary($connection); | ||
$flds = " | $flds = " | ||
Line 171: | Line 172: | ||
$sql1 = $datadict-> | $sql1 = $datadict-> | ||
$sql2 = $datadict-> | $sql2 = $datadict-> | ||
- | Data Types | + | |
+ | </ | ||
+ | |||
+ | ===== Data Types ===== | ||
Stick to a few data types that are available in most databases. Char, varchar and numeric/ | Stick to a few data types that are available in most databases. Char, varchar and numeric/ | ||
Line 177: | Line 181: | ||
Different databases have different ways of representing dates and timestamps/ | Different databases have different ways of representing dates and timestamps/ | ||
+ | <code php> | ||
$date1 = $connection-> | $date1 = $connection-> | ||
$date2 = $connection-> | $date2 = $connection-> | ||
+ | </ | ||
We also provide functions to convert database dates to Unix timestamps: | We also provide functions to convert database dates to Unix timestamps: | ||
+ | <code php> | ||
$unixts = $recordset-> | $unixts = $recordset-> | ||
- | For date calculations, | + | </ |
+ | For date calculations, | ||
+ | |||
+ | <code php> | ||
$sql = ' | $sql = ' | ||
- | The maximum length of a char/varchar field is also database specific. You can only assume that field lengths of up to 250 characters are supported. This is normally impractical for web based forum or content management systems. You will need to be familiar with how databases handle large objects (LOBs). ADOdb implements two functions, UpdateBlob( ) and UpdateClob( ) that allow you to update fields holding Binary Large Objects (eg. pictures) and Character Large Objects (eg. HTML articles): | + | </code> |
+ | The maximum length of a char/ | ||
+ | |||
+ | <code php> | ||
# for oracle | # for oracle | ||
$conn-> | $conn-> | ||
Line 194: | Line 207: | ||
$conn-> | $conn-> | ||
$conn-> | $conn-> | ||
+ | |||
+ | </ | ||
Null handling is another area where differences can occur. This is a mine-field, because 3-value logic is tricky. | Null handling is another area where differences can occur. This is a mine-field, because 3-value logic is tricky. | ||
In general, I avoid using nulls except for dates and default all my numeric and character fields to 0 or the empty string. This maintains consistency with PHP, where empty strings and zero are treated as equivalent, and avoids SQL ambiguities when you use the ANY and EXISTS operators. However if your database has significant amounts of missing or unknown data, using nulls might be a good idea. | In general, I avoid using nulls except for dates and default all my numeric and character fields to 0 or the empty string. This maintains consistency with PHP, where empty strings and zero are treated as equivalent, and avoids SQL ambiguities when you use the ANY and EXISTS operators. However if your database has significant amounts of missing or unknown data, using nulls might be a good idea. | ||
- | ADOdb also supports a portable | + | ADOdb also supports a portable |
- | Stored Procedures | + | ===== Stored Procedures |
Stored procedures are another problem area. Some databases allow recordsets to be returned in a stored procedure (Microsoft SQL Server and Sybase), and others only allow output parameters to be returned. Stored procedures sometimes need to be wrapped in special syntax. For example, Oracle requires such code to be wrapped in an anonymous block with BEGIN and END. Also internal sql operators and functions such as +, ||, TRIM( ), SUBSTR( ) or INSTR( ) vary between vendors. | Stored procedures are another problem area. Some databases allow recordsets to be returned in a stored procedure (Microsoft SQL Server and Sybase), and others only allow output parameters to be returned. Stored procedures sometimes need to be wrapped in special syntax. For example, Oracle requires such code to be wrapped in an anonymous block with BEGIN and END. Also internal sql operators and functions such as +, ||, TRIM( ), SUBSTR( ) or INSTR( ) vary between vendors. | ||
An example of how to call a stored procedure with 2 parameters and 1 return value follows: | An example of how to call a stored procedure with 2 parameters and 1 return value follows: | ||
+ | <code php> | ||
+ | switch ($db-> | ||
+ | { | ||
+ | case ' | ||
+ | $sql = ' | ||
+ | break; | ||
+ | case ' | ||
+ | $sql = " | ||
+ | break; | ||
+ | default: | ||
+ | die(' | ||
+ | } | ||
+ | # @RETVAL = SP_RUNSOMETHING @myid, | ||
+ | $stmt = $db-> | ||
+ | $db-> | ||
+ | $db-> | ||
+ | # true indicates output parameter | ||
+ | $db-> | ||
+ | $db-> | ||
+ | </ | ||
- | switch ($db-> | ||
- | case ' | ||
- | $sql = ' | ||
- | case ' | ||
- | $sql = | ||
- | " | ||
- | break; | ||
- | default: | ||
- | die(' | ||
- | } | ||
- | # @RETVAL = SP_RUNSOMETHING @myid, | ||
- | $stmt = $db-> | ||
- | $db-> | ||
- | $db-> | ||
- | # true indicates output parameter | ||
- | $db-> | ||
- | $db-> | ||
As you can see, the ADOdb API is the same for both databases. But the stored procedure SQL syntax is quite different between databases and is not portable, so be forewarned! However sometimes you have little choice as some systems only allow data to be accessed via stored procedures. This is when the ultimate portability solution might be the only solution: treating portable SQL as a localization exercise... | As you can see, the ADOdb API is the same for both databases. But the stored procedure SQL syntax is quite different between databases and is not portable, so be forewarned! However sometimes you have little choice as some systems only allow data to be accessed via stored procedures. This is when the ultimate portability solution might be the only solution: treating portable SQL as a localization exercise... | ||
- | SQL as a Localization Exercise | + | ===== SQL as a Localization Exercise |
In general to provide real portability, | In general to provide real portability, | ||
+ | <code php> | ||
$sqlGetPassword = ' | $sqlGetPassword = ' | ||
$sqlSearchKeyword = quot;SELECT * FROM articles WHERE match (title, | $sqlSearchKeyword = quot;SELECT * FROM articles WHERE match (title, | ||
+ | |||
+ | </ | ||
In our main PHP file: | In our main PHP file: | ||
+ | <code php> | ||
# define which database to load... | # define which database to load... | ||
$database = ' | $database = ' | ||
Line 242: | Line 264: | ||
# search for a keyword $word | # search for a keyword $word | ||
$rs = $db-> | $rs = $db-> | ||
- | Note that we quote the $word variable using the qstr( ) function. This is because each database quotes strings using different conventions. | ||
- | Final Thoughts | + | </ |
- | The best way to ensure | + | Note that we quote the $word variable |
- | Visit the following page for more references on database | + | ===== Final Thoughts ===== |
+ | |||
+ | The best way to ensure that you have portable SQL is to have your data tables designed using sound principles. Learn the theory | ||
(c) 2002-2014 John Lim. | (c) 2002-2014 John Lim. |
v5/userguide/portable_sql.txt · Last modified: 2020/12/30 21:32 by peterdd