Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2012
    Posts
    2

    Unanswered: taking user input from keyboard(not source code)

    if we have to insert records into a mysql database using c api then the general code is this
    Code:
    if (mysql_query(conn, "insert into empinfo values ('saikat banerjee')")) 
      {
          printf("4Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
          exit(1);
      }
    but, here we have to enter the record from the code itself .

    but, i want to enter records from direct user inputs.
    like, save the user input in a say, string variable and then use that string variable to store the record in the database. ie. i ant to do something like this
    Code:
    char empname[100]
    then i ask for user input
    Code:
    printf("please enter a employee name");
      fgets(empname,100,stdin);
      printf("%s",empname);
    and then,
    Code:
    if (mysql_query(conn, "insert into empinfo values (empname)")) 
      {
          printf("4Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
          exit(1);
      }
    but, this is storing NULL in the table.

    is there any way to do this?
    please help!

  2. #2
    Join Date
    Sep 2009
    Location
    San Sebastian, Spain
    Posts
    880
    The insert is a string that has to be generated try the following:

    char query[1024];
    sprintf(query, "INSERT INTO empinfo VALUES ('%s')", empname);

    then inside mysql_query pass the conn and the query string above and this should work. There are other ways where you bind values to parameters but this is a good first step.

    if (mysql_query(conn, query))
    {
    printf("4Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
    exit(1);
    }
    Last edited by it-iss.com; 01-10-12 at 13:18. Reason: used PHP sprintf function. This is correct for C/C++
    Ronan Cashell
    Certified Oracle DBA/Certified MySQL Expert (DBA & Cluster DBA)
    http://www.it-iss.com
    Follow me on Twitter

  3. #3
    Join Date
    Jan 2012
    Posts
    2
    thanks a lot! it works fine!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •