I tried to reproduce your case. Look here:
script.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);
}
Database test
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;
output
$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"
}
}
The output means, that while statement was executed once and prints all the rows, that the query should return, which is absolutely correct, because fetchAll returns an array of arrays with all the rows. PHP interprets it as true and while runs once.
While foreach
will iterate over the array of arrays and you will have the corresponding row every time.