I used to have this as one of the options (4th param) passed to PDO constructor:
$aOptions[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES utf8";
But just found that it does not work on certain php versions on Windows (does not work in 5.3) due to some bug.
Now I need to run SET NAMES utf8
using either $pdo->exec("SET NAMES utf8");
or $pdo->query("SET NAMES utf8");
right after the instantiating the pdo object. So, which one should I use - exec() or query()?
query runs a standard SQL statement without parameterized data. Best practice is to stick with prepared statements and execute for increased security. See also: Are PDO prepared statements sufficient to prevent SQL injection?
PDO::query() prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object.
To prepare and execute a single SQL statement that accepts no input parameters, use the PDO::exec or PDO::query method. Use the PDO::exec method to execute a statement that returns no result set. Use the PDO::query method to execute a statement that returns one or more result sets.
PDO::query() returns a PDOStatement object, or FALSE on failure.
When using PDO::EXEC
the result returned is not of an PDOStatement
but an integer of the rows affected.
When using PDO::QUERY
the result returned is a PDOStatement
.
So the answer is it depends on what you need to do with the data, if you need to run query and not do anything with the results, then you should use exec
to execute the query, otherwise if you need the number of rows, the data returned you should use pdo::query
and then use the results returned by the call.
in regards to the bug there are several work around that you can take
PDO_MYSQL
MYSQL_ATTR_INIT_COMMAND
with 1002
the second issue may have some issues on 64bit's OS's and Some windows configurations.
Bug Information: http://bugs.php.net/bug.php?id=47224
PDO::exec() should be used for queries that do not return a resultset, such as a delete statement or 'set'. PDO::query() should be used when you expect a resultset to be returned. It returns a PDOStatement object to you that you can iterate over to get the individual rows. Note though that if you're using data from an untrusted source in your queries prepared statements would be the best way to go for either kind of query (but you probably knew that).
So, in your case PDO::exec() would be right. Are you sure though that passing the set names command to PDO::__construct() as the last value doesn't work? It works for me and I have PHP 5.3 on Windows. Could you post some more sample code of what you're doing?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With