0

I have an database that I need to validate a user input against. I can't figure out the syntax for the while loop I'm using to validate the input.

Expecting:

/*
User inputs "Hondas" 
Console checks database if "Hondas" exists.
If it doesn't exist, prompt user again.
If it does exist, continue w/ program.
*/

Current Code:

            // Open a connection to MySQL 
            conn = new MySqlConnection(cs);
            conn.Open();

            //Declare DataReader
            MySqlDataReader rdr = null;

            // Form SQL Statement
            string stm = $"select count(*) from vehicle where make = \"{sqlInput}\"";

            // Prepare SQL Statement
            MySqlCommand cmd = new MySqlCommand(stm, conn);

            rdr = cmd.ExecuteReader();

            // Output Results
            while (rdr.Read() && rdr.GetInt32(0) <= 0)
            {
                Console.Clear();
                Console.WriteLine("This make doesn't exist in the database, try again.");
                sqlInput = Console.ReadLine();
            // I believe I'm supposed to have some connection info here.
            }

This successfully validates however the loop doesn't work properly. It only runs one time if I have multiple Incorrect entries. I'm not terribly familiar with how the connection should look. Thanks for the help.

  • 2
    Possible duplicate of [What are good ways to prevent SQL injection?](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection) – mjwills Dec 01 '18 at 22:05
  • Your execution of the SQL must be **inside the loop**. Your `while` loop would become something like `while (firstInvocation || (rdr.Read() && rdr.GetInt32(0) <= 0))` and then set `firstInvocation` to `true` before the loop and `false` inside the loop. – mjwills Dec 01 '18 at 22:05
  • @mjwills I think that would work, however see my solution I found below. let me know if you can think of something better. –  Dec 01 '18 at 22:10
  • Also consider `while (shouldContinue)`. Then set `shouldContinue` to `true` before the loop, and set it to `rdr.Read() && rdr.GetInt32(0) <= 0)` at the end of the loop (inside the loop). – mjwills Dec 01 '18 at 22:12

0 Answers0