Unable to use ConnectionManager for inserting data

Once of the worst documentation.

Argument 1 passed to Cake\Database\Query::insert() must be of the type array, string given, called in /var/www/html/staging/src/Controller/Component/DatabaseComponent.php on line 141

Please share the code you’re trying to use that causes this error.

@Zuluru Thankyou for your reply

$this->connection = ConnectionManager::get(‘default’);
$insertSatet = $this->connection->insert($table, $insertData);
return $insertSatet->lastInsertId($table);

this is my code

What exactly is $insertData, and why are you using this instead of ORM methods that work with entities?

@Zuluru its an associative array with column name as key and value as column value. Initially it was working fine but today it broke. This same coding style is already implemented in two of my live projects and there it works fine.

eg: $insertData = [“id”=>1,“name”=>“test”];

I’ve never used this particular interface (the ORM is so much better for 99% of applications), but it looks like this should work. I guess I’d check to make sure that right at the time you’re calling it, it really does have that, and not, for example, a string with a serialized or JSON-encoded version of what you expect.

This works for me without any problems:

/** @var \Cake\Database\Connection $connection */
$connection = \Cake\Datasource\ConnectionManager::get('default');
$lastID = $connection->insert('categories', [
    'name' => 'This is a Test',
    'lft' => 0,
    'rght' => 0
])->lastInsertId('categories');

The fact that your error literally says Argument 1 passed to Cake\Database\Query::insert() must be of the type array, string given means that you do something like

$connection = \Cake\Datasource\ConnectionManager::get('default');
$connection->insert('categories', 'somestring');

somewhere in your code or somewhere in your $insertData variable.

If you are 100% certain its not that array then you maybe are doing the same thing somewhere else in your code where you are currently not expecting it to throw that error.

Looking at the whole stacktrace will tell you where you come from to reproduce that error.