I want to get the number of rows that have been add from an INSERT query but that give me this error:

Error: Call to a member function rowCount() on a non-object

This API page mentionned that we can get the number of affected lines for a DELETE, INSERT or UPDATE statement.

I use a MySQL databse.
Here's my code, the bug appear at the last line:

$query = db_insert('wysiwyg')
  ->fields(array('format', 'editor', 'settings'))
  ->values(array(
    'format' => 'filtered_html',
    'editor' => '',
  ))
  ->values(array(
    'format' => 'full_html',
    'editor' => 'tinymce',
  ))
  ->values(array(
    'format' => 'plain_text',
    'editor' => '',
  ))
  ->execute();
$num = $query->rowCount();

Thanks

Comments

renzor’s picture

Assigned: Unassigned » renzor
Category: bug » support
Status: Active » Closed (won't fix)

http://api.drupal.org/api/drupal/includes%21database%21query.inc/class/I...

When inserting data into the database, a queryobject (connection object) will be returned, where rowCount() doesn't exist.
It doesn't really make sense to count the amount of inserted rows, since you know the data that's being inserted.

gielfeldt’s picture

Category: support » feature
Status: Closed (won't fix) » Active

It doesn't really make sense to count the amount of inserted rows, since you know the data that's being inserted.

I beg to differ.

Consider this pseudo-example:

<?php
$query = db_select('table1', 't')
  ->fields('t')
  ->condition('t.col1', $somevalue1)
  ->condition('t.col2', $somevalue2);

$result = db_insert('table2')
  ->from($query)
  ->execute();

$number_of_rows_inserted = $result->rowCount();
?>

This scenario is not unlikely. However, the above code of course won't work, since $result does not implement rowCount(). You could argue, that one could just run a countQuery() on the first $query object, but that would be inefficient, especially on large data sets.

Instead, we are currently forced to do:

<?php
$result = db_query("INSERT INTO {table2} SELECT * FROM {table1} t WHERE t.col1 = :somevalue1 AND t.col2 = :somevalue2", array(
  ':somevalue1' => $somevalue1,
  ':somevalue2' => $somevalue2,
));

$number_of_rows_inserted = $result->rowCount();
?>

Now this isn't really that bad. Except when you for example need something like a LIMIT clause in the select query, which may implemented differently for some backends as there's no SQL99 standard for this.

I'm therefore changing this ticket to a feature request.

gielfeldt’s picture

Status: Active » Closed (works as designed)

My bad. This feature is actually present in another form, using the return option Database::RETURN_AFFECTED:

<?php
$query = db_select('table1', 't')
  ->fields('t')
  ->condition('t.col1', $somevalue1)
  ->condition('t.col2', $somevalue2);

$number_of_rows_inserted = db_insert('table2', array('return' => Database::RETURN_AFFECTED))
  ->from($query)
  ->execute();

?>