我正在使用PHP PDO连接到MySQL数据库并返回结果集,但我似乎得到了重复输出,尽管我的数据库中只有2条记录。
MYSQL:
mysql> SELECT * FROM nouns;
+-----+---------------+---------+
| PID | german | english |
+-----+---------------+---------+
| 1 | die Männer | men |
| 2 | die Frauen | women |
+-----+---------------+---------+
2 rows in set (0.00 sec)
mysql>
PHP代码段1:
$database = new MySQLConnect();
$database->query("SELECT german, english FROM nouns;");
while ($row = $database->row()->fetch()) {
foreach ($row as $value) {
$data .= $value;
}
PHP代码段2:
interface IMySQLSettings
{
const HOSTNAME = "hostname";
const DATABASE = "database";
const USERNAME = "username";
const PASSWORD = "password";
function __construct();
function query($query);
function row();
}
class MySQLConnect implements IMySQLSettings
{
private $hostname = IMySQLSettings::HOSTNAME;
private $database = IMySQLSettings::DATABASE;
private $username = IMySQLSettings::USERNAME;
private $password = IMySQLSettings::PASSWORD;
private $connect;
private $query;
function __construct()
{
$this->connect = new PDO("mysql:host=$this->hostname;dbname=$this->database", $this->username, $this->password);
$this->connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
function query($query)
{
try {
$this->query = $this->connect->prepare("$query");
$this->query->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
}
function row()
{
return $this->query;
}
}
输出:
die Männerdie Männermenmendie Frauendie Frauenwomenwomen
答案 0 :(得分:2)
也许在构建PDO对象时添加此行
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
更多信息PDO fetch_style
这是你从php.net手册获得的:
PDO::FETCH_ASSOC
Array
(
[NAME] => apple
[COLOUR] => red
)
PDO::FETCH_BOTH
Array
(
[NAME] => banana
[0] => banana
[COLOUR] => yellow
[1] => yellow
)
答案 1 :(得分:0)
重构版本,取出了所有无用的代码,但需要添加所需的功能。
class MySQLConnect
{
private $connect;
function __construct()
{
$dsn = "mysql:host=".IMySQLSettings::HOSTNAME.";dbname=".IMySQLSettings::DATABASE;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$this->connect = new PDO($dsn, IMySQLSettings::USERNAME,IMySQLSettings::PASSWORD, $opt);
}
function query($query, $params = array())
{
$stmt = $this->connect->prepare($query);
return $stmt->execute($params);
}
}
$db = new MySQLConnect();
$stmt = $db->query("SELECT german, english FROM nouns");
foreach ($stmt as $row) {
foreach ($row as $value) {
$data .= $value;
}
虽然我保留了IMySQLSettings的东西,但它完全是无用的作为界面。
如果我需要另一个数据库连接怎么办?重新定义MySQLConnect以实现另一个接口?
而不是花哨的inteerface,它必须只是一个数组,传递给MySQLConnect的构造函数。