我正在使用 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