4

I'm using raw queries with laravel 4, is there a way to check affected rows on an insert? DB::getPdo()->rowCount(); gives me an "undefined method" error. Code is as follows:

$query = "INSERT IGNORE INTO table (id) VALUES (?)";
$doQuery = DB::insert($query, array($value));
if ($doQuery) {
    return DB::getPdo()->last();
} else {
    return 0;
}

If not, is there an easy way to figure out whether an insert was done or not without making it two queries?

Komal12
  • 3,340
  • 4
  • 16
  • 25
Felix
  • 610
  • 2
  • 9
  • 21

2 Answers2

9

You can use this function:

int affectingStatement(string $query, array $bindings = array())

Run an SQL statement and get the number of rows affected.

Parameters

  • string $query
  • array $bindings

Return Value

  • int

This function is already documented for laravel 4.2 as well as for 5.4. [Edit note: The documentation for those versions are removed from the laravel site.]

Note that insert() is an alias for statement() and will return a boolean. While the functions update() and delete() are aliases for affectingStatement(). So if you want to be funny and confuse the reviewers you could also write $rowCount = DB::delete("INSERT IGNORE ...", $bindings) - and it will work.

Paul Spiegel
  • 30,925
  • 5
  • 44
  • 53
  • 5.4 link is broken aswell - I removed both. 8.x API can be found [here](https://laravel.com/api/8.x/Illuminate/Database/Connection.html#method_affectingStatement). – Paul Spiegel Feb 10 '21 at 15:47
3

Well I figured out a workaround that should be just as efficient - use INSERT INTO instead of INSERT IGNORE INTO and use try/catch.

   $query = "INSERT INTO table (id) VALUES (?)";
    try {
        DB::insert($query, array($value));
        return 1;
    } catch (\Exception $e) {
        return 0;
    }
koalaok
  • 5,075
  • 11
  • 47
  • 91
Felix
  • 610
  • 2
  • 9
  • 21