Search code examples
c++stringpersistencelibpqxx

C++ Encode string to string literals programmatically


I'm trying to persist text that is input from some user into a db, how would I encode these values? I'm a n00b in C/C++ and am having trouble with my google fu skills..

I'm using libpqxx and trying to do something like

std::string sql = "insert into chat values (nextval('chat_seq'), '" + userInput + "');";
work.exec(sql);

but when userInput is something like

I'm doing just fine

My insertion will fail. Thanks for your help.


Solution

  • As mentioned in the comments, look up SQL injection, there is a ton of resource on it.

    https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet http://www.veracode.com/security/sql-injection

    A good start would be to identify the characters that cause injection and escape them or remove/replace the characters.

    make sure userInput is a string and you have access to all the useful std string bits to do string maniupulation such as substr, replacement etc.

    see: http://www.cplusplus.com/reference/string/string/