Execute batch MySQL array of queries

/** * Define a custom exception class */ class InvalidVarsException extends Exception { // Redefine the exception so message isn't optional public function __construct($message, $code = 0, Exception $previous = null) { // make sure everything is assigned properly parent::__construct($message, $code, $previous); } // custom string representation of object public function __toString() { return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; } } // Usually your wrapper for data you can extend ... class extra_SQL extends Data { /** * @param $sql * * @return string * * This can execute individual queries from an array, and if there is more than 1 query passed in the same string it will break it down and execute each one * * ...also always pass by reference in PHP functions if you're not modifying - only reads & no writes - it's faster and better memory handling internally. */ protected function execute_batch_array(&$sql) { $return = ''; $rs = NULL; if(!is_array($sql) || count($sql) === 0) { throw new InvalidVarsException('Pass arrays only! ... on ' . __LINE__ . ' in ' . __CLASS__ . ' within ' . __FILE__ . "\r\n"); } else { foreach($sql as $query) { /** * this is batch processing without PDO * checks to make sure it's a string since the substr_count works with arrays, and looking for statement separators * * --semicolons ";" are "\x3b" * --array_filter will remove the elements created with tabs or spaces so they aren't executed against the MYSQLI query function */ if(substr_count($query, ';') > 1) { $queries = explode("\x3b", trim($query)); $queries = array_filter($queries); foreach($queries as $query_part) { $rs = $this->db_conn->query($query_part); } } else { $rs = $this->db_conn->query($query); } if(!empty($rs)) { $return .= "\n\nSuccessfully executed:\n{$query}\n\n"; } else { $return .= "\n\nUnsuccessfully executed:\n{$query}\n\n"; } unset($rs); } } return $return; } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.