Page 1 of 1

PDO::FETCH_ASSOC Question

Posted: Fri Nov 30, 2018 5:04 am
by Addos
:roll: I'm trying to learn OOP and convert some old scripts to the latest. (Testing all this locally) I can't see why I cannot get either of the loops to work below. If I comment out var_export($row); everything gets out-putted so I know my connection and query is OK.
Any ideas as to what else I need to try as I've exhausted my research at the mo ?
Thank you.

Code: Select all

<?PHP $stmt = $pdo->prepare("SELECT * FROM queue ORDER BY customer_name ASC");
			$stmt->execute();
			$row = $stmt->fetchAll(PDO::FETCH_ASSOC);

			if(!$row) exit('No rows');
	echo $stmt->rowCount();
			//var_export($row);
			//$stmt = null; 

   while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
	   
	   echo $row['date_due'];
	   echo $row['customer_name'];
	}
	
	$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
	foreach($results as $row) {
		
		echo $row['date_due'];
	    echo $row['customer_name'];
} ?>

Re: PDO::FETCH_ASSOC Question

Posted: Fri Dec 14, 2018 10:16 pm
by Christopher
$stmt->fetchAll(PDO::FETCH_ASSOC); will fetch all the rows selected, so you are at the end of the dataset. You don't need to loop. Either use fetchAll() or loop and use fetch(),