Reading and Writing to MySQL

Documentation

MySQL

PHP

Tutorials

http://phpmaster.com/avoid-the-original-mysql-extension-1/

http://phpmaster.com/migrate-from-the-mysql-extension-to-pdo/

http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

http://www.dreamincode.net/forums/topic/214733-introduction-to-pdo/

PDO

It's quite amazing how long it has taken the web to catch-up to best practices adopted by client/server computing from 20 years ago—PDO is a perfect example. PDO is a data access interface that works with several databases, and it should be your first choice when creating a new PHP site.

Making a Database Connection

  1. define ('ENVIRONMENT', 'PxPro Dev'); //PxPro Server || PxPro Dev || Production
  2. //Tweak these lines for your database server
  3. $dbPort = '3306';
  4. if (ENVIRONMENT === 'PxPro Server') {
  5. $dbHost = 'mysql:host=localhost';
  6. $dbDb = 'YourDatabaseName';
  7. $dbUserId = 'UserName';
  8. $dbPassword = 'YourPassword';
  9. } else if (ENVIRONMENT === 'PxPro Dev') {
  10. $dbHost = 'mysql:host=localhost';
  11. $dbDb = 'YourDatabaseName';
  12. $dbUserId = 'UserName';
  13. $dbPassword = 'YourPassword';
  14. } else if (ENVIRONMENT === 'Production') {
  15. $dbHost = 'mysql:host=subdomain.domain.com';
  16. $dbDb = 'YourDatabaseName';
  17. $dbUserId = 'UserName';
  18. $dbPassword = 'YourPassword';
  19. }
  20. //Probably ought not touch these.
  21. $dbDSN = "$dbHost;port=$dbPort;dbname=$dbDb";
  22. $db; //this will be a global variable
  23. if (ENVIRONMENT === 'PxPro Server') {
  24. define('DOMAIN', 'http://' . $_SERVER['HTTP_HOST'] . '/');
  25. } else if (ENVIRONMENT === 'PxPro Dev') {
  26. define('DOMAIN', 'http://' . $_SERVER['HTTP_HOST'] . '/~Craig/DART/');
  27. } else if (ENVIRONMENT === 'Production') {
  28. define('DOMAIN', 'http://' . $_SERVER['HTTP_HOST'] . '/');
  29. }
  30. define('APP_ROOT', dirname(dirname(__FILE__)) . '/'); //double-pumping to go up one level since this file is in a sub-directory.
  31. define('INCLUDE_ROOT', APP_ROOT . "includes/");
  32.  
  33. function makeDbConnection() {
  34. global $dbDSN;
  35. global $dbUserId;
  36. global $dbPassword;
  37. global $db;
  38. try {
  39. $db = new PDO($dbDSN, $dbUserId, $dbPassword, array(
  40. PDO::ATTR_PERSISTENT => true,
  41. PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
  42. ));
  43. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  44. $db->exec("SET CHARACTER SET utf8");
  45. } catch(PDOException $e) {
  46. debug("unable to make connection: ".$e->getMessage());
  47. $delayedError .= print($e->getMessage());
  48. }
  49. }

PDO Data Access Using a Variable

This works for both reads (Select) and writes (Insert/Update/Delete).

global $db;
try {
	$stmt = $db->prepare("Select * From departments Where deptId = ?;");
	$stmt->execute(array($this->deptId));
	if ($row = $stmt->fetchObject()) {
		$this->deptId = $row->deptId;
		$this->department = $row->department;
	}
	$stmt->closeCursor();
	return $this->deptId;
} catch(PDOException $e) {
	debug('Dept / load() / ' . $e->getMessage());
	return false;
}

PDO Read Using Static Statement

This works for reading from the database.

try {
	$stmt = $db->query("Select count(*) as aNumber from pages;");
	if ($row = $stmt->fetchObject()) {
		$aNumber = $row->aNumber;
	}
} catch(PDOException $e) {
	echo "<!-- Unable to query table pages: " . $e->getMessage() . ' -->' . PHP_EOL;
}

This works for writes (Insert/Update/Delete).

try {
	$stmt = $db->exec("Insert pages (pageName, pageType) values ('myPage', 'STD');");
	$newPageId = $db->lastInsertId();
} catch(PDOException $e) {
	echo "<!-- Unable to query table pages: " . $e->getMessage() . ' -->' . PHP_EOL;
}

Formatting Values for Data Access

Dreamweaver method; not recommended. Click to show...

Literals

Literals need to be delimited by:

Strings: single quotes (it is possible to use double quotes if ANSI_QUOTES is turned off).

Numbers: Just type the number. Valid characters are 0-9 + − e . (period).

Dates: Date and time values can be represented in several formats, such as quoted strings or as numbers, depending on the exact type of the value and other factors. For example, in contexts where MySQL expects a date, it interprets any of '2015-07-21', '20150721', and 20150721 as a date. The time format is 'YYYY-MM-DD HH:MM:SS'.

You should not use a column alias (presumable table aliases are OK) in the Where clause in MySQL.

Basic MySQL DML Syntax

  1. Select column1, column2
  2. From tableName
  3. Where column3 = 'a string value';
  4.  
  5. Select a.col1 As first, a.col2, b.col1
  6. From table1 As a Left Join table2 As b
  7. On a.pk = b.fk
  8. Where a.dateCol >= '2012-03-29'
  9. Order by a.col2 Desc;
  10.  
  11. Insert tableName (col1, col2, col3)
  12. Values (123, 'abc', '2012-03-28');
  13. Insert tableName (col1, col2, col3)
  14. Select colA, colB, colC
  15. From myTable;
  16.  
  17. Update tableName
  18. Set col1=123, col2='abc', col3='2012-03-28');
  19.  
  20. Delete from tableName
  21. Where col1<900;

Basic MySQL DDL Syntax

  1. Create table myTableName (
  2. col1 int not null AUTO_INCREMENT,
  3. col2 char(3),
  4. col3 varchar(255),
  5. col4 datetime,
  6. Constraint myTableNamePK Primary Key (col1)
  7. );

Common Data Types

data type storage comments
TINYINT 1 byte The signed range is -128 to 127. The unsigned range is 0 to 255.
SMALLINT 2 bytes The signed range is -32768 to 32767. The unsigned range is 0 to 65535.
INT 4 bytes The signed range is -2147483648 to 2147483647. The unsigned range is 0 to 4294967295.
DECIMAL(p,s) varies Exact fixed point number. p = precision or total number of digits, s = scale or number of decimal places.
DOUBLE varies Floating point number.
DATE    
DATETIME    
CHAR(p) p bytes p can be 0 to 255, see the doco for the weird use of char(0)
VARCHAR(p) p bytes The range of p is 0 to 65,535.