Insert user input into mysql

Hi! I have this piece of code, I want to write the user input into db. The problem is that the variables are of multiple types, int and strings. What am I doing wrong/ I can t compile it.
I have hidden the server, user and other info. thx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 #include <iostream>
#include<string>
// For MySQL Connection
#include <mysql.h>

using namespace std;

// Defining Constant Variables
#define SERVER ""
#define USER ""
#define PASSWORD ""
#define DATABASE "bankdb"

int qstate;
int main()
{
	MYSQL *connect;
	MYSQL_ROW row;
	MYSQL_RES *res;
	connect = mysql_init(NULL);
	if (!connect)
	{
		cout << "Mysql Initialization Failed";
		return 1;
	}

	connect = mysql_real_connect(connect, SERVER, USER, PASSWORD, DATABASE, 0, NULL, 0);

	if (connect)
	{
		int id;
		string fName, lName, pass;
		cout << "Enter ";
		cin >> id;
		cin >> fName;
		cin >> lName;
		cin >> pass;
		
		string query = "INSERT INTO customers(account,firstName,lastName,password) VALUES ( '" + id + "', '" + fName + "', '" + lName + "', '" + pass + "')";

		if (qstate != 0)
		{
			cout << mysql_error(connect) << endl << endl;
			return 1;
		}
		cout << endl << endl;
	}


	mysql_close(connect);
	system("pause");
	return 0;
}
}
Last edited on
Use a string stream to build your string.
http://www.cplusplus.com/reference/sstream/
It doesn't take work. :(
Maybe I should make all the database entries strings. It keeps inserting null values that 's what I mean by it doesn't work
Last edited on
the database insert statement should work exactly like it would in a sql connectivity tool to the database. You type integers in base 10 as strings in those:
insert into blah col 1 values 12345 where stuff
something like that, right? 12345 is just text when you do that.
your insert library call should do that same exact thing.

if it does not work, what I would do is print the sql statement that you sent to the DB and try to run it from your sql tool to see if it works there. You may also see the problem immediately when printed out.

some other stuff:
you may need to check that your connection worked differently.
you may need to wait until you have confirmed the connection, some DB take many MS to respond and you may be spamming the DB server, eg 'connect' and then 2 nanoseconds later query, and its still connecting so it fails out. So instead of 'if connect' you may want to say
while (!connect && sometimer < 2 seconds); //wait, wait, wait, ok connected

if (connect) //it either timed out or connected or errored at this point, right?

talking to other machines is tedious. You spend half your time waiting on them to get their act in gear, in my experience.
Last edited on
Topic archived. No new replies allowed.