Posted By

kendsnyder on 05/27/11


Tagged

mysql database


Versions (?)

PHP Simplified DB Functions


 / Published in: PHP
 

  1. // simple DB access functions
  2. function dbGetConn() {
  3. static $conn;
  4. if (!$conn) {
  5. $conn = mysql_connect(DB_HOST, DB_USER, DB_PASS)
  6. or die('Error connecting: ' . mysql_error());
  7. }
  8. return $conn;
  9. }
  10.  
  11. function dbSelect($sql) {
  12. $rs = mysql_query($sql, dbGetConn());
  13. if (!$rs) {
  14. die('Invalid query: ' . mysql_error());
  15. }
  16. $results = array();
  17. while (($row = mysql_fetch_object($rs))) {
  18. $results[] = $row;
  19. }
  20. return $results;
  21. }
  22.  
  23. // return a hash of data like array(100,200,300)
  24. // or when two columns are selected, like array('a'=>100,'b'=>200,'c'=>300)
  25. function dbSelectHash($sql) {
  26. $rs = mysql_query($sql, dbGetConn());
  27. if (!$rs) {
  28. die('Invalid query: ' . mysql_error());
  29. }
  30. // get the first row so we can check if there are one or two columns selected
  31. $row = mysql_fetch_array($rs, MYSQL_NUM);
  32. if (!$row) {
  33. return array();
  34. }
  35. $results = array();
  36. if (count($row) == 1) {
  37. // one column selected; just use numeric keys
  38. $results[] = $row[0];
  39. while (($row = mysql_fetch_array($rs, MYSQL_NUM))) {
  40. $results[] = $row[0];
  41. }
  42. }
  43. else {
  44. // two or more columns selected; use the first column value as the key and the second column value as the value
  45. $results[$row[0]] = $row[1];
  46. while (($row = mysql_fetch_array($rs, MYSQL_NUM))) {
  47. $results[$row[0]] = $row[1];
  48. }
  49. }
  50. return $results;
  51. }

Report this snippet  

You need to login to post a comment.