我试图重现你的情况。看这里:
脚本.php
<?php
$host = 'localhost';
$user = "user";
$password = '';
$db_name = 'test';
$port = 3306;
try
{
$connection = new PDO("mysql:host=$host;port=$port;dbname=$db_name", $user, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
$page=$connection->prepare("SELECT * FROM Document");
$page->execute();
while ($row = $page->fetchAll(PDO::FETCH_ASSOC)) {
var_dump($row);
}
数据库测试
DROP TABLE IF EXISTS `Document`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Document` (
`DataID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Description` varchar(50) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`DataID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Document`
--
LOCK TABLES `Document` WRITE;
/*!40000 ALTER TABLE `Document` DISABLE KEYS */;
INSERT INTO `Document` VALUES (1,'!!!'),(2,'This is document 2'),(3,'This is document 3'),(4,'This is document 4'),(5,'Hello');
/*!40000 ALTER TABLE `Document` ENABLE KEYS */;
UNLOCK TABLES;
输出
$php script.php
array(5) {
[0]=>
array(2) {
["DataID"]=>
string(1) "1"
["Description"]=>
string(3) "!!!"
}
[1]=>
array(2) {
["DataID"]=>
string(1) "2"
["Description"]=>
string(18) "This is document 2"
}
[2]=>
array(2) {
["DataID"]=>
string(1) "3"
["Description"]=>
string(18) "This is document 3"
}
[3]=>
array(2) {
["DataID"]=>
string(1) "4"
["Description"]=>
string(18) "This is document 4"
}
[4]=>
array(2) {
["DataID"]=>
string(1) "5"
["Description"]=>
string(5) "Hello"
}
}
输出意味着,while 语句执行一次并打印所有行,查询应该返回,这是绝对正确的,因为 fetchAll 返回包含所有行的数组数组。PHP 将其解释为 true 并且 while 运行一次。
Whileforeach
将遍历数组数组,每次都会有相应的行。