One: Yes, you are right. If you pass an array as a parameter to the execute
method, then it will handle it as a bound parameter, and will consider it as a string (PDO::PARAM_STR
).
Two: Yes, but you have to use it together with either bindParam()
, bindValue()
, or a parameterized execute()
. You have to make sure, that you escape all the data, which has ever came from a user (such as a form post, or query string).
Three: Yes, according to >this< Stackoverflow answer, it is just as you've described it.
Four: Yes, and no: yes, because it's optional (they are just constant integer values). No, fetchAll(PDO::FETCH_ASSOC)
is not the same as fetchAll()
. If you use the option parameter when you instantiate the PDO class, then you can change the default fetch mode to use with fetchAll()
. For example:
$params = array(
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$db = new PDO("mysql:host=" . $host . ";dbname=" . $dbname, $user, $pwd, $params);
You can also use the setAttribute()
method on an existing instance to set the default fetch mode in a quite similar way:
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
The results are the same. Any subsequent fetch()
or fetchAll()
calls without a parameter will use the fetch mode you've set, or until the instance is alive.
The default fetch mode is PDO::FETCH_BOTH
, which returns an array with both associative indexes, and zero-started numerical indexes, such as the example below:
Array
(
[0] => Array
(
[id] => 675
[0] => 675
[some_value] => foo
[1] => foo
)
[1] => Array
(
[id] => 681
[0] => 681
[some_value] => bar
[1] => bar
)
)
Five: I'm not quite sure what do you mean. It is possible to use unnamed parameters in PDO, but if you pass an associative array to execute()
, then it will show you an error. The way to get around that, is to call array_values()
on your array, when you're passing it to execute()
. Example:
$parameters = array(
"id" => 123,
"some_value" => "foo"
);
$db->prepare("SELECT * FROM table_name WHERE id = ? AND some_value = ?");
$db->execute(array_values($parameters));
For union
operator (and similar items) you should use named parameters only. see here
Six: Using try-catch is completely optional, and it depends on your implementation and error-handling preference. I prefer using exceptions with try-catch, but you can use warnings or silent error codes, as described at the relevant section of the PDO::SetAttribute documentation >here<.
These can be set up using either the option parameter during PDO instantiation, or using the setAttribute()
method on an existing PDO instance. Example:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*
PDO::ERRMODE_EXCEPTION can be replaced with either
PDO::ERRMODE_SILENT or PDO::ERRMODE_WARNING
*/
If something's not clear, or you think I haven't provided a thorough answer on that part, then please let me know, and I'll update the answer.