-4

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

kluzix
  • 11
  • 2
  • 5
    You can `+` concatenate objects of type `std::string` but not c-style strings. – bitmask Sep 23 '22 at 20:29
  • is it an option to do this with char – kluzix Sep 23 '22 at 20:31
  • C++ is not the kind of language you can guess your way through. Adding a pointer to a string literal has no meaning. `+` does not do what you are imagining it does. – Drew Dormann Sep 23 '22 at 20:33
  • 3
    That question tells me that maybe you would benefit from [getting a decent book and learn the basics](https://stackoverflow.com/q/388242/430766) before proceeding. – bitmask Sep 23 '22 at 20:34
  • Are you a Java programmer, by any chance? What you are doing (using `+`) looks llike an attempt to use something that works in Java (or similar languages), but does not work in C++. If this is the case, do not use Java (or any other language) as a model in writing C++ code. All you will wind up with is 1) Buggy code, 2) Inefficient code, 3) Code that looks weird to a C++ programmer. – PaulMcKenzie Sep 23 '22 at 20:42
  • Correction to the above: `+` works exactly as you expect it to, but only if you use it on the correct types. the semantics around `char *` date back about 50 years and made pretty good sense at the time. – user4581301 Sep 23 '22 at 20:44
  • BTW, care with string concatenation to build query, see [xkcd: exploits of mom](https://xkcd.com/327/). Look for *'bind parameters'*. – Jarod42 Sep 23 '22 at 23:49

1 Answers1

2

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    The last paragraph is, or at least closely related to, the [Saga of Little Bobby Tables](https://xkcd.com/327/) – user4581301 Sep 23 '22 at 20:48