I must use raw sql queries in my Symfony 5 application in order to improve the performance of some operations. But I cannot manage to bind my parameters to the query althoug it does not throw any errors. It just adds the new row in database with all the fields setup to NULL.
Here is how I do it :
$sql = "INSERT INTO `brand` (name, created_at) VALUES (name=:name, created_at=:date)";
$connection = $this->em->getConnection();
$statement = $connection->prepare($sql);
$statement->bindValue(':name', $data);
$statement->bindValue(':date', $now);
$statement->executeQuery();
return $connection->lastInsertId();
Dumpin my statement, I can see the sql query and the params array well established. The dump :
Doctrine\DBAL\Statement {#939 ▼
#sql: "INSERT INTO brand (name, created_at) VALUES (name=:name, created_at=:date)"
#params: array:2 [▼
":name" => "Hyundai"
":date" => "2024-10-23 14:37:13"
]
#types: array:2 [▶]
#stmt: Symfony\Bridge\Doctrine\Middleware\Debug\Statement {#934 ▶}
#platform: Doctrine\DBAL\Platforms\MySQL57Platform {#621 ▶}
#conn: Doctrine\DBAL\Connection {#446 ▶}
}
Returning the "lastInsertId" show me the expected result. But in my database (I'm using HeidiSql, this new line which has indeed the returned id has a Null value on all its fields...
I have tried putting those params as an array directly in the execute() call with the same result. I have tried with one simple string parameter to check if a simple worked worked but to no avail. I have also tried to precise the parameter type in the bindValue calls (using \PDO::PARAM_STR, exemple led on a string parameter). Finally, I have put the params values directly in $sql without having to safely bind them after. Here again, I find NULL values in my database.
I do not know what I'm doing wrong here...
Problem solved !
Not having the habits to use raw sql, I think my stupid brain made an hybrid of SQL and DQL.
I needed to change :
"INSERT INTO brand (name, created_at) VALUES (name=:name, created_at=:date);";
into :
"INSERT INTO brand (name, created_at) VALUES (:name, :date);"