J R
J R

Reputation: 1

How to print only 1 line from database to C++

for my program I have few lines of questions stored in my database database.

I want my program to display 1 line at a time. For now my output prints out all the lines at the same time.

example.

I don't know what should be the code to print out only one particular line.

void quiz()
{
    int difficulty;
    
    system("cls");
    cout<<"Choose your difficulty\n 1. EASY || 2. MEDIUM || 3. HARD\n";
    cin>>difficulty;
    
    if(difficulty==1)
    {
        MYSQL_ROW row;
        MYSQL_RES* res;
        int i=0;
        
        cout<<"You have choosen EASY DIFFICULTY questions";
        system("cls");

        int qstate=mysql_query(obj, "SELECT * FROM questions");
        if(!qstate)
        {
            res = mysql_store_result(obj);
            while(row = mysql_fetch_row(res))
            {
                fflush(stdin);
                cout<<"Question no : "<<i+1<<endl;
                cout<<row[1]<<endl;
            
                
            }
                    
        }
        else
        {
            cout<<"Failed to fetch";
        }   
            
    }
    else if(difficulty==2)
    {
        cout<<"You have choosen MEDIUM DIFFICULTY questions";
    }
    else if(difficulty==3)
    {
        cout<<"You have choosen HARD DIFFICULTY questions";
    }
    else
    {
        system("cls");
        cout<<"Wrong Choice Select Again!!!\n";
        quiz();
    }
}

Upvotes: 0

Views: 394

Answers (1)

jkb
jkb

Reputation: 2450

You explicitly told it to iterate over all the returned database rows and print them with this code:

            while(row = mysql_fetch_row(res))
            {
                fflush(stdin);
                cout<<"Question no : "<<i+1<<endl;
                cout<<row[1]<<endl;
            
                
            }

Ignoring the flush(stdin), which you don't want, this loop says "As long as there is data to fetch, print it."

Also the <<i+1 part is not incrementing i, it is just adding one to zero then printing that which is why all your lines say "Question 1".

Upvotes: 1

Related Questions