PHP MySQL Multiple (Batch) Queries

Did you know, you can execute multiple queries in PHP using the mysqli extension. Its pretty easy as you can see:

<?      
$connection = new mysqli($dbHost, $dbUser, $dbPass, $dbName);

if ($connection->connect_error) 
{
   echo "Error Occurred While Connection To DataBase";
}


//SQL statements separated by semi-colons

$sqlStatements = "INSERT INTO dbName (columnName) VALUES ('Value1');INSERT INTO dbName (columnName) VALUES ('Value2');INSERT INTO dbName (columnName) VALUES ('Value3');";
 
$sqlResult = $connection->multi_query($sqlStatements);
 
if($sqlResult == true) 
{
   echo 'Successfully executed all statements.';
} 
else 
{
   echo 'Error occurred executing statements.';
}
?>


Clearly, this is more efficient than executing queries one by one, and could save a bit of time in critical applications. Also, mysqli is object-orientated, so there are other useful variables and method that can be returned from the mysqli object to make your code more efficient.

Errors? You may need to enable the mysqli extensions, as these may not be enabled by default. See here http://www.php.net/manual/en/mysqli.installation.php for more info, or leave a comment with your problem.

5 comments: