I made those 2 posts to improve my code, but can someone can explain to me what is the difference between this php vulnerable code and this secure code. I know the first one is insecure and can be subject to SQL injections and the other no, but why this type of coding is strong ?
Your question seems to be:
Q: Why is a parameterized query less vulnerable than a "raw" query?
Please read this:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
Frankly, it should be MANDATORY READING for anybody interested in "secure coding":
Primary Defenses Defense Option 1: Prepared Statements (with Parameterized Queries)
The use of prepared statements with variable binding (aka parameterized queries) is how all developers should first be taught how to write database queries. They are simple to write, and easier to understand than dynamic queries. Parameterized queries force the developer to first define all the SQL code, and then pass in each parameter to the query later. This coding style allows the database to distinguish between code and data, regardless of what user input is supplied.
Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker. In the safe example below, if an attacker were to enter the userID of tom' or '1'='1, the parameterized query would not be vulnerable and would instead look for a username which literally matched the entire string tom' or '1'='1.
This is just one of many SQL-related issues you should be aware of. The OWASP article lists others, and has links to many other important topics.