Hi, i've been working on this simple homework assignment and the only thing stopping me from finishing it is passing a c++ variable to a mysql query using mysql_query. I've searched around for about an hour and every potential solution I have found hasn't worked, so I figured maybe if someone took a look at the exact code I had they could help. So here it is.

#include <iostream>
#include <mysql.h>
using namespace std;
MYSQL *connection, mysql;
MYSQL_RES *result;
MYSQL_ROW row;
int query_state;
int main()
{
   mysql_init(&mysql);

connection =mysql_real_connect(&mysql,"students","********","********","********",0,0,0);
   if(connection == NULL){
      cout << "ERROR";
      cout << mysql_error(&mysql)<<endl;
      return 1;
    }
   int num;
   cout << "Please enter a customer number: " << endl;
   cin >> num;
   query_state = mysql_query(&mysql, "select ORDER_DATE FROM ORDERS WHERE ORDER_NUM =" + num);
   if (query_state !=0) {
   cout << mysql_error(connection) << endl;
   return 1;
}
result = mysql_store_result(connection);
while ( ( row = mysql_fetch_row(result)) != NULL )
{
   cout << row[0] << endl;
}  
   return 0;
}

I put ***'s in for privacy. Any help would be greatly appreciated.

Recommended Answers

All 2 Replies

"select ORDER_DATE FROM ORDERS WHERE ORDER_NUM =" + num

You cannot simply combine a character string with an integer by simply use operator +. "select ORDER_DATE FROM ORDERS WHERE ORDER_NUM =" returns an address of where character string store and if you add num to that address, it cuts num numbers of beginner characters. For example:

int main()
{
    std::cout << "select ORDER_DATE FROM ORDERS WHERE ORDER_NUM =" + 3;
    // OUTPUT IS: ect ORDER_DATE FROM ORDERS WHERE ORDER_NUM =
    return 0;
}

One of the easiest way to solve your problem is to use string class and then ask user for string input rather than integer input. Then combine the input and the SQL query together.

string sqlQuery;
    
    cout << "Please enter a customer number: " << endl;
    cin >> sqlQuery;
    
    sqlQuery = "select ORDER_DATE FROM ORDERS WHERE ORDER_NUM = " + sqlQuery;
    query_state = mysql_query(&mysql, sqlQuery.c_str());

Don't forget to include #include <string> .

I hope this will help.

Thank you very much it worked!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.