I am quite new to kirby and try to figure out some strange errors. I am using Version 4.4.1, PHP 8.2 and apache. I try to use the database implemention of kirby. That works well for updates and selects but doesn’t work for insert (yes, I use autoincrement for the id column).
I also store some files to the database (mediumblob) which may work or not, maybe depending on the file content.
Can I use kirby to do this things, can kirby work with MariaDB (mysqli) or shall I use my own implementation of database access?
Could you share more context of your current use case and implementation, so that we can see where it’s going wrong or Kirby is hitting its limits? Thanks!
Thanks, that helps a lot to actually understand your question.
I’ll ping @lukasbestle as I think he has more experience with databases than me.
Two instant thoughts:
Your SQL query ends with WHERE email = '%s' AND hash = '%s', but I don’t see a hash column in your database table.
What exactly is the escdata function doing? Could that maybe corrupt the file contents before you store them in the database? Or, do you have to unescape them after reading from the database?
Yes. After you load the uploaded file into memory with file_get_contents(), the $data['file01'] value is a binary string with the file contents.
Is there a specific reason you use esc() on all fields of your data? Please keep in mind that escaping always needs to be context-sensitive. The default context for esc() is HTML. This can be useful if you want to print the fields to an HTML page.
But it’s cleaner and safer to do the escaping on output (as close to your template output as possible), not on input into your database. This ensures that your database contains reusable content for different contexts and also reduces the risk of vulnerabilities due to output in an unexpected context.
Another recommendation from skimming through your code: Using sprintf() to build SQL queries from dynamic data is very unsafe as it allows SQL injection attacks. You can protect against this with a prepared statement. Your database engine will then take care of filling in the dynamic values in a safe way that avoids SQL injections.
thank you for your answer. You are definitely right that the code with sprintf() in its current state is vulnerable to SQL injections and needs to be changed.
The error with the files was the csvdata() function. I changed the Db::update call. For what I tested, it works.
BTW: You don‘t need Db::escape() either. Kirby’s higher-level database methods like Db::update() automatically take care of using prepared statements wherever possible.