問題描述
我曾經(jīng)把它作為傳遞給 PDO 構(gòu)造函數(shù)的選項(xiàng)(第 4 個參數(shù))之一:
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";
但剛剛發(fā)現(xiàn)由于某些錯誤,它在 Windows 上的某些 php 版本上不起作用(在 5.3 中不起作用).
But just found that it does not work on certain php versions on Windows (does not work in 5.3) due to some bug.
現(xiàn)在我需要使用 $pdo->exec("SET NAMES utf8");
或 $pdo->query("SET NAMES utf8");
在實(shí)例化 pdo 對象之后.那么,我應(yīng)該使用哪個 - exec() 或 query()?
right after the instantiating the pdo object. So, which one should I use - exec() or query()?
推薦答案
當(dāng)使用 PDO::EXEC
返回的結(jié)果不是 PDOStatement
而是整數(shù)的受影響的行.
When using PDO::EXEC
the result returned is not of an PDOStatement
but an integer of the rows affected.
當(dāng)使用 PDO::QUERY
時,返回的結(jié)果是一個 PDOStatement
.
When using PDO::QUERY
the result returned is a PDOStatement
.
所以答案取決于你需要對數(shù)據(jù)做什么,如果你需要運(yùn)行查詢而不對結(jié)果做任何事情,那么你應(yīng)該使用 exec
來執(zhí)行查詢,否則如果需要行數(shù),返回的數(shù)據(jù)應(yīng)該使用pdo::query
,然后使用調(diào)用返回的結(jié)果.
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.
- http://www.php.net/manual/en/pdo.查詢.php
- http://php.net/manual/en/pdo.exec.php
關(guān)于該錯誤,您可以采取多種解決方法
in regards to the bug there are several work around that you can take
- 安裝
PDO_MYSQL
- 將
MYSQL_ATTR_INIT_COMMAND
替換為1002
- 將您的 PHP 更新到已通過并修補(bǔ)的最新穩(wěn)定版本.
第二個問題可能在 64 位操作系統(tǒng)和一些 Windows 配置上有一些問題.
the second issue may have some issues on 64bit's OS's and Some windows configurations.
錯誤信息:http://bugs.php.net/bug.php?id=47224
這篇關(guān)于PDO::exec() 還是 PDO::query()?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!