Such a general practice is called "whitelisting".
You are positively right about this vulnerability. And for a junior developer you have a very good eye. As a matter of fact, most people who call themselves "professionals" never bother themselves with such questions.
So, to prevent an ordinary SQL injection and also to prevent random access to table fields (a user may be disallowed to some of them), you have to verify your post data against a pre-written whitelist.
Here you can see my approach for either classic mysql or PDO as an example.