First you should never trust user inputs. Let’s take an example.
Assume that you have following code to run in php
$id = $_POST['id'];
$mysqli -> query('SELECT * FROM users WHERE id = $id');
So what if an user send a malicious string input as the id like
1 OR 1 = 1; DELETE DATABASE db1
Your database will completely be deleted.
You can prevent this by using mysqli prepared statements. As of PHP 5.x, 7.x there’s the default library mysqli with itself.
It works in this way
First creates a prepared statement (mysql session with the db)
Then sends the parameters or data to the db server
Finally executes the statement.
However, you can not use prepared statements in the way you used to use normal mysql queries. I strongly recommend you to read php.net’s articles on prepared statements.
Note: Either you can use prepared statements with procedural or with OOP mysqli style
Finally, where should you use prepared statements?
uhm. It is a hard question. But, even a big company (which uses mysql and php) uses those in their every query. It’s a good practice. The best thing is performance tests shows, prepared queries are faster than normal queries, also can be easily used inside loops.