Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use PDO to run multiple SQL queries and retrieve the number of rows affected for each statement?

Tags:

php

pdo

Here's what I've got so far:

/**
 * @param PDO $db
 * @param string $file
 */
function run_sql_file($db, $file) {
    $sql = file_get_contents($file);
    try {
        $affected = $db->exec($sql);
        println("$affected row(s) affected");
    } catch(PDOException $e) {
        exitmsg($e->getMessage());
    }
}

It does seem to run all the queries, but it always give me back "0 rows affected". Is there a way to get the number of rows affected for each statement? Preferably along with the associated query, and any error messages and warnings.

like image 457
mpen Avatar asked Jan 22 '26 07:01

mpen


1 Answers

I met the same issue, for example I am reading a series of mysql drop table sqls from a file and I want to execute them into a single PDO->exec():

    $dbh = new PDO('mysql:host=test;dbname=db1', 'user', 'pass');
  try {

    $dbh->exec('drop table test_table1;drop table test_table2;');
  }
catch(PDOException $e)
{
    echo $e->getMessage();
    die();
}

If the first drop sql is successful then no Exception is rised even if the second one failed(that table name doesn't exist anymore). It seems there is no way you can check wether all of the sqls were executed or not with PDO_MYSQLND; only if the first one fails then a PDO Exception is rised.

like image 157
Galileo_Galilei Avatar answered Jan 23 '26 23:01

Galileo_Galilei