lime icon

Phosphorus and Lime

A Developer's Broadsheet

This blog has been deprecated. Please visit my new blog at klenwell.com/press.
PHP: MySQL statements in heredocs
Detailed my problem on Usenet/Google Groups/GUBA:

http://groups.google.com/group/comp.lang.php...


The only response I got wasn't much help so I went out and found the answer myself.

It's right here:

http://www.php.net/manual/en/function.mysql-query.php#37870

The problem: like me, the PHP mysql_query() function can only handle 1 statement at a time. The manual isn't quite explicit on the point, but does note:

The query string should not end with a semicolon.


Kudos to Predrag Supurovic. I cleaned up his batch function slightly:

/* fx mysql_query_batch
source: http://www.php.net/manual/en/function.mysql-query.php#31381
*************************************************/
function mysql_query_batch($query, $as_transaction=TRUE)
{
// *** DATA

# internal
$_SPLIT = array();

# return
$query_result = 0;


// *** MANIPULATE

# transaction-safe query
if ( $as_transaction )
{
$query = 'START TRANSACTION;' . $query . '; COMMIT;';
}

# split query
$_SPLIT = preg_split("/[;]+/", $query);

# process statements one-by-one
foreach ( $_SPLIT as $_statement )
{
$_statement = trim($_statement);

if ( !empty($_statement) )
{
# try query
$query_result = mysql_query($_statement);

# catch
if ( !$query_result )
{
trigger_error('MySQL error number '.mysql_errno().': '.mysql_error());
break;
}
}
}


// *** RETURN

return $query_result;

} # end Fx
/*______________________________________________*/


Plugged it in. So far, so good.

keywords: PHP, MySQL, heredoc, sql, multiple statements, batch, syntax, error