Return to Snippet

Revision: 46879
at May 27, 2011 03:13 by kendsnyder


Initial Code
// simple DB access functions
function dbGetConn() {
	static $conn;
	if (!$conn) {
		$conn = mysql_connect(DB_HOST, DB_USER, DB_PASS) 
			or die('Error connecting: ' . mysql_error());
	}
	return $conn;
}

function dbSelect($sql) {
	$rs = mysql_query($sql, dbGetConn());
	if (!$rs) {
		die('Invalid query: ' . mysql_error());
	}
	$results = array();
	while (($row = mysql_fetch_object($rs))) {
		$results[] = $row;
	}
	return $results;
}

// return a hash of data like array(100,200,300)
// or when two columns are selected, like array('a'=>100,'b'=>200,'c'=>300)
function dbSelectHash($sql) {
	$rs = mysql_query($sql, dbGetConn());
	if (!$rs) {
		die('Invalid query: ' . mysql_error());
	}
	// get the first row so we can check if there are one or two columns selected
	$row = mysql_fetch_array($rs, MYSQL_NUM);
	if (!$row) {
		return array();
	}
	$results = array();
	if (count($row) == 1) {
		// one column selected; just use numeric keys
		$results[] = $row[0];
		while (($row = mysql_fetch_array($rs, MYSQL_NUM))) {
			$results[] = $row[0];
		}		
	}
	else {
		// two or more columns selected; use the first column value as the key and the second column value as the value
		$results[$row[0]] = $row[1];
		while (($row = mysql_fetch_array($rs, MYSQL_NUM))) {
			$results[$row[0]] = $row[1];
		}	
	}
	return $results;
}

Initial URL


Initial Description


Initial Title
PHP Simplified DB Functions

Initial Tags
mysql, database

Initial Language
PHP