How run two or more SQL queries together in the same line command?

February 15, 2016 28.1k views
Nginx MySQL Ubuntu


I want run multiple queries (sql) in the same line command to Update image URLs in my database of WordPress.

How I run that command connecting the comands of updates?

For example:

UPDATE wpposts SET postcontent = replace(postcontent, '',');
posts SET postcontent = replace(postcontent, '',');
UPDATE wpposts SET postcontent = replace(post_content, '',');

I am using nginx - Ubuntu 14.

2 Answers

It's best to put these in a shell script:

echo "This program will update blahblahblah..."
echo "After starting this program, enter your database password for root"

mysql -u root -p <<-ENDMARKER

 UPDATE wp_posts SET post_content = replace(post_content, '','); 
 UPDATE wp_posts SET post_content = replace(postcontent, '',');
 UPDATE wp_posts SET post_content = replace(post_content, '',');


Make the script file executable after saving. The script method is better than using the pipe method so you can debug the script in stages, or later expand on it when you have more junk you need to cleanup.

Because you mentioned WordPress, I will provide a PHP-specific answer:

$mysqli = new mysqli("", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;

do {
    if ($res = $mysqli->store_result()) {
} while ($mysqli->more_results() && $mysqli->next_result());

Example of PHP's mysqli-multi-query()


Have another answer? Share your knowledge.