Do i have to write PREPARE before query in PDO

Please see the 2 codes below.
one has PREPARE in it and other doesnot have PREPARE.
do i have to write “PREPARE” before query in PDO ?
Are both below queries same and secure ?
will both the code do same thing ?

$sql = "select * from table";
$q = $conn->query($sql);

and this

$sql = $conn->prepare("SELECT * FROM table");

What happens if you try them?


yes both queries return same correct data.

But i want to ask
Do i have to write prepare in query

You need to learn the meaning of the words (language keywords) you are using, not just repeating things you have seen. This is where the dictionary (documentation) for the language you are using comes in -

The main point of using a prepared query, first preparing, then executing it, is to separate the parsing of the sql query syntax from the evaluation of data values, in order to prevent any sql special characters in a value from being able to break the sql query syntax, which is how sql injection is accomplished. A secondary purpose is to provide a performance improvement for queries that will be executed, usually with different data values, more than once per instance of your script.

The query you have shown has no data value being supplied to it, and ir probably only being executed once, therefore, there’s no point in using a prepared query, and in fact, due to the two communications needed with the database server, will actually take more time. You would just use the query() method for a query that doesn’t have any data being supplied to it, that is only being executed one time per instance of your script.



Thanks mabismad and sibertius

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.