//*************************************************************************************** // C Insert/Update data into a Mysql database //*************************************************************************************** #include #include #include #include int main() { MYSQL *conn; const char *server = "localhost"; // Host server address const char *user = "demo2"; // Database username const char *password = "demo2"; // Database password const char *database = "demo2"; // Database name char fname[20]; char lname[20] ; char addr[100]; char flavor[20]; char top[20]; char cc[10]; printf("Enter first name: "); scanf("%s", fname); printf("Enter last name: "); scanf("%s", lname); printf("Enter address: "); scanf("%s", addr); // scanf("%[^\n]", addr); //allow entry of spaces printf("Enter ice cream flavor: "); scanf("%s", flavor); printf("Enter ice cream topping: "); scanf("%s", top); printf("Enter credit card type: "); scanf("%s", cc); // Initialize the connection conn = mysql_init(NULL); if (!conn) { fprintf(stderr, "mysql_init() failed \n"); return EXIT_FAILURE; } // Connect to the database if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { fprintf(stderr, "mysql_real_connect() failed. Error: %s\n", mysql_error(conn)); mysql_close(conn); return EXIT_FAILURE; } char sql[100]; sprintf(sql,"INSERT INTO cust_order " \ "VALUES(%d,'%s','%s','%s','%s','%s','%s',%d)", \ 0, fname, lname, addr, flavor, top, cc, 1 ); //0 for auto_increment // printf("%s\n",sql); //for debug only // Execute SQL query int ok = mysql_query(conn, sql); if (ok != 0) { fprintf(stderr, "SELECT insert failed. Error: %s\n", mysql_error(conn)); mysql_close(conn); return EXIT_FAILURE; } mysql_close(conn); printf("Data updated successfully.\n"); return EXIT_SUCCESS; }