1

I am trying to insert post data inside a Joomla table. So within a loop I populate the query with the values of a decoded json but all the time I get this error: Column count doesn't match value count at row 1

Here is my code:

 $columns = array('column1','column2','column3','column4');

$query = $db->getQuery(true);

foreach($arrayDecodedJson as $key => $value)
{
                
    $query
        ->insert($db->quoteName('#__table_name_'))
        ->columns($db->quoteName($columns))
        ->values(implode(',', $db->quote($value)));

    $db->setQuery($query);

    $db->execute();
}

The $value is an array with values I want to insert into the already existed table.

The $arrayDecodedJson keys and the columns are the same.

The data after var_dump($arrayDecodedJson) are like:

array( 'key1'=>'value1','key2'='value2') , array( 'key1'=>'value3','key2='value4'),
... array( 'key1'=>'valueN','key2'='value'N)

0
1

Although the other answer works, it's not very efficient. Instead everything but $query->values() call can be done outside the loop. This way multiple rows are inserted with a single database query:

$query = $db->getQuery(true)
    ->insert($db->quoteName('#__table_name_'))
    ->columns($db->quoteName($columns));

foreach($arrayDecodedJson as $row)
{
    $query->values(implode(',', $db->quote($row)));
}

$db->setQuery($query)->execute();
1

The solution was simple.

  1. Put $query = $db->getQuery(true);, inside the foreach loop.
  2. Make an array in order to put inside the arrays values like :
$values = array($db->quote($value['value1']),$db->quote($value['value2']),$db->quote($value['value3']),$db->quote($value['value4'])

Then you make the query like so inside the foreach loop:

              $query
                  ->insert($db->quoteName('#__table_name'))
                  ->columns($db->quoteName($columns))
                  ->values(implode(',',$values));
              $db->setQuery($query);
              $db->execute();

I hope that it will help someone!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.