function _DatabaseHandler::db_query

4.x _DatabaseHandler.php _DatabaseHandler::db_query($sql_query)
5.x _DatabaseHandler.php _DatabaseHandler::db_query($sql_query, $args = array())

This function is used to perform a database query. It can take simple replacement patterns, by using ?. If you actually need to have a ? in the query, you can escape it with ??. For example: $result = $db->db_query("SELECT * FROM table WHERE name = '?' and age = ? ", $name, $temp_age);

Parameters

unknown_type $sql_query:

Return value

unknown

File

classes/_DatabaseHandler.php, line 252

Class

_DatabaseHandler

Code

function db_query($sql_query) {

  // If there were any arguments to this function, then we must first apply
  // replacement patterns.
  $args = func_get_args();
  array_shift($args);
  if (is_array($args [0])) {
    // If the first argument was an array, it means we passed an array of values instead
    // of passing them directly.  So use them directly as our args.
    $args = $args [0];
  }

  // The query may contain an escaped ?, meaning "??", so I will replace that with something
  // else first, then change it back afterwards.
  $sql_query = str_replace("??", "~ESCAPED_Q_MARK~", $sql_query);

  // If $c (number of replacements performed) does not match the number of replacements
  // specified, warn the user.
  if (substr_count($sql_query, "?") != count($args)) {
    fpm("<br><b>WARNING:</b> Replacement count does not match what was supplied to query: $sql_query<br><br>");
  }

  if (count($args) > 0) {
    // Replace each occurance of "?" with what's in our array.

    foreach ($args as $replacement) {
      // Escape the replacement...
      // The replacement might ALSO have a question mark in it.  Escape that too.
      if (strpos($replacement, "?") !== 0) {
        $replacement = str_replace("?", "~ESCAPED_Q_MARK~", $replacement);
      }

      // Because mysql_real_escape_string will allow \' to pass through, I am going to
      // first use mysql_real_escape_string on all slashes.
      $replacement = str_replace("\\", mysql_real_escape_string("\\"), $replacement);
      // Okay, perform the replacement
      $replacement = mysql_real_escape_string($replacement);

      // If we have a $ followed by a number (like $99), preg_replace will remove it.  So, let's escape the $ if so.
      /// if so.
      $replacement = addcslashes($replacement, '$');

      $sql_query = preg_replace("/\?/", $replacement, $sql_query, 1);

    }

  }

  $sql_query = str_replace("~ESCAPED_Q_MARK~", "?", $sql_query);

  //////////////////////////////////////////////

  // Run the sqlQuery and return the result set.
  $result = mysql_query($sql_query, $this->dbc);
  if ($result) 
   {
    return $result;
  }
  else {
    // Meaning, the query failed...
    // Do nothing.  Do not attempt to log anything, as that could cause an infinite loop.			

    // Display the error on screen
    $this->db_error();
  }
}