Tidbit Tuesday on PHP: Simple MySQL Database Query Function

It’s always great to create functions for those things you do a lot.  Probably the single most common function I execute is database calls.

Here is a simple script for hitting up your MySQL database with a query:

<?php
   if(!function_exists(dbQuery)) {
      function db_query($cfg_array, $query) {
         $connection =
            mysql_connect(
               $cfg_array['db_loc'],$cfg_array['db_user'],$cfg_array['db_pass']
            ) or die(mysql_error());

         mysql_select_db($cfg_array['db_name'],$connection)
            or die(mysql_error()." >> ".$query);
         $result = mysql_query($query,$connection)
            or die (mysql_error()." >> ".$query);
         $i = 0;

         if($result != 1) {
            while ($data_array = mysql_fetch_array($result)) {
               foreach($data_array as $key => $value) {
                  $tableArray[$i][$key] = stripslashes($data_array[$key]);
               }

               $i++;
            }

            return $tableArray;
         }
      }
   }
?>

You should be able to just copy and paste this as a function and call it in one of two ways:

$cfg_array = array(
   "db_loc" => 'www.databaselocation.com',
   "db_user" => 'some user'
   "db_pass" => 'some password'
   "db_name" => 'database_name_here'
);

$query = "SELECT * FROM 'table' WHERE some_column = 'something'";

db_query($cfg_array, $query); // This will return an array with the table in it.

$query = "UPDATE/DELETE/ETC * FROM 'table' WHERE some_column = 'something'";

db_query($cfg_array, $query); // This will return return an empty array, but still works.

I use this function in EVERYTHING.  I also have some other functions that use this as its base.  Someday I’ll turn it into a class.

So, what do you think?