In the last article, we learned how to provide named parameters for PDO. You can access it at this link: https://www.hcode.com.br/blog/consulta-pdo-com-passagem-de-parametros-no-php-7-parte-1
Now, in this post we will learn about positional parameters. We will use the same example from the previous article
Positional Parameters
These parameters do not expect an identifier, but just a question mark (?). It will inform PDO that a parameter for the SQL script will be defined there
Notice that the query is exactly the same. What changed were the parameters themselves, as you can see highlighted in red
Now, when calling the bindParam() method, we will provide the position of the parameter as the first argument, a number starting at 1. That’s why it’s called “Positional Parameters”
Finally, we will call the execute() method again:
Did the data get inserted into the Database?
It continues to work, excellent!
Named Parameters vs Positional Parameters
After these examples, we need to answer one question: what is the difference between named parameters and positional parameters? Both work the same way and have the same objective. Practically speaking, positional parameters require more attention on our part since they follow the order of the provided parameters. Therefore, more caution is needed to avoid confusing one parameter's position with another
Now you are ready to provide parameters to PDO and also to choose when to use each type of parameter, so that your PHP projects become increasingly professional :)
See you in the next article!