Passing argument into const char *

Viewed 57

I want to make mysql query it look like this:

SELECT name FROM AUTHORS where name LIKE %[here argument]%

I search for solution and i find putting arg in "+[arg]+" like this;

  const char * author = getString("Author: ", 100).c_str();
  // res type MYSQL_RES* res
  res = exec_query(conn, "select name from authors where name like '%"+author+"%'");

But i gives me an error:

expression must have integral or unscoped enum type

1 Answers

You have two problems with your code:

  • you are storing a dangling pointer in author

  • you are trying to concatenate multiple const char* pointers.

Change your code to treat author and your concatenated SQL as std::string instead. You can use std::string::c_str() when passing the final SQL string to mysql, eg:

std::string author = getString("Author: ", 100);
// res type MYSQL_RES* res
std::string sql = "select name from authors where name like '%"+author+"%'";
res = exec_query(conn, sql.c_str());

Do be aware that the code above is subject to SQL Injection attacks. You really should be using a parameterized query instead.

Related