Skip to content

Multiple MySQL queries in a single string, using PHP

I recently got stung trying to execute multiple SQL “do something”-style queries in PHP e.g.

$query = "TRUNCATE TABLE `table_a`; TRUNCATE TABLE `table_b`;";
$result = mysql_query($query);

The problem is that PHP doesn’t actually support multiple queries in the same call. I kept getting “there’s an error in your syntax near”.. style error messages, and it drove me MAD – my syntax was great, and I knew it worked fine.

A brief read of the PHP.net manual for mysql_query revealed the answer (emphasis mine):

mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that’s associated with the specified link_identifier.

Rather than go through the hassle of breaking my pre-existing SQL query into smaller chunks (my actual query was substantially larger than the example above), I went for the automated solution.

I hereby give you mysql_multiquery()

function mysql_multiquery($sql, $identifier = NULL)
{
  $queries = preg_split("/;+(?=([^'|^\\\']*['|\\\'][^'|^\\\']*['|\\\'])*[^'|^\\\']*[^'|^\\\']$)/", $sql);
  foreach ($queries as $query) {
    if (strlen(trim($query)) > 0) 
    {
      if ($identifier) 
        mysql_query($query, $identifier);
      else
        mysql_query($query);
    }
  }
}

Important note: This function does not return results. It’s strictly for executing multiple setup or installation-style queries

Thanks to Dev-Explorer for the inspiration and the RegEx

Automatically save and load Vim views / folds

Many people have written about ways of getting the Vim editor to automatically save and load views / folds. I’ve tried most of the solutions, and they all had various problems.

When placing code similar to the following in my .vimrc file usually gave me errors when opening a new tab or split:

au BufWinLeave * silent! mkview
au BufWinEnter * silent! loadview

So, after reading this .vimrc file (Don’t ask me how I found it), I’ve switched to using the following instead:

set viewoptions-=options
augroup vimrc
    autocmd BufWritePost *
    \   if expand('%') != '' && &buftype !~ 'nofile'
    \|      mkview
    \|  endif
    autocmd BufRead *
    \   if expand('%') != '' && &buftype !~ 'nofile'
    \|      silent loadview
    \|  endif
augroup END

Voila! Error-free automatically saved folds:)

Move a Magento category using code

Magento is a very powerful e-commerce system, however the developer-facing documentation is pretty light (read: missing) for some very basic things.

After relentless Googling and trawling through the Magento API, I finally found the following:

$categoryId = 456;
$parentId = 123;

$category = Mage::getModel('catalog/category')->load($categoryId);
$category->move($parentId, null);
Follow

Get every new post delivered to your Inbox.