I will answer your question trying to be objective and brief:
► a. Directly
A query must be passed to the database manager directly only if no data from the outside is involved in the query, because that data that the user enters can be manipulated or modified by a malicious user to prepare an injection of malicious code.
An example of a query that can be passed without risk directly, because the parameter 5
is written in the query would be:
SELECT id, nombre FROM tabla WHERE id=5;
However, if 5 is passed in a variable, you can not pass the query directly:
SELECT id, nombre FROM tabla WHERE id=$id;
//riesgo grave de inyección
This injection could occur not only at the SQL level, but at other levels of the system.
► b. Through prepared consultations
Conversely to to , prepared queries should always be used if the data comes from external sources. The API that you are using as an intermediary between the program and the database (PDO or MySQLi) will be responsible for eliminating the risk of injection, if you use this methodology well .
For example, this is a secure query:
$strSQL="SELECT id, nombre FROM tabla WHERE id=?";
$stmt=$pdo->prepare($strSQL);
$arrParams=array($id);
$stmt->execute($arrParams);
On the other hand, this query is not safe, you can already know why:
$strSQL="SELECT id, nombre FROM tabla WHERE id=? OR id=$id";
$stmt=$pdo->prepare($strSQL);
$arrParams=array($id);
$stmt->execute($arrParams);
That means that it is not enough to use prepared queries, you also have to use them in the right way.
Also, in the case of PDO, you must make sure that the query emulation attribute is turned off ( FALSE
), because otherwise you could get an injection emulating prepared queries.
► c. Transactions
In short, they are used when you need to handle lots of data in your CRUD. Suppose you are going to insert or update one thousand or one million records. You start the process and at some point there is a failure. How will you know the records that were inserted / updated? You could lose weeks / months comparing data to know what you have to insert / update and what you do not. The transactions allow you to handle that process safely and cleanly, because if something goes wrong, you can reverse everything that has been done so far.
In the transaction you tell the BD: do all this, or do not do anything to me .
About the transactions, the PHP Manual explains it very well here: Transactions and autoconsignation ("auto- commit ")
From all this you can talk much more. I wanted to give a brief answer, that of an idea of the differences of use.