$emp = $statement->fetch(PDO::FETCH_ASSOC); while($emp != null) { //process this record $emp = }//end while $statement->closeCursor(); The sample code first does a fetch, Fetch and display one priming assigning the record data to a variable (note record at a time $emp is singular) As long as the record is not null, the code processes the record, then fetches the next record Note the method is not called closeCursor all records have been fetched. If you plan your application properly, most queries won’t return a lot of data. makes returning the data to the control fetchAll very easy. Using Parameter Queries Though prepared statements work well with simple queries, their real value comes when you use them for parameter queries SQL Injection attacks avoided To create parameter queries, you must : first define a query that includes parameters prepare the query program variables to parameters bind execute the Parameters come in two flavors: and named unnamed(aka question mark parameters) We’ll start with named parameters $city = 'Stevens Point'; $myQuery = 'Select * From tblStudents ' . 'Where city = :city ' . 'Order By LastName, FirstName'; $statement = $db->prepare($myQuery); $statement->bindValue(':city', $city); $statement->execute();
$emp = $statement->fetch(PDO::FETCH_ASSOC); while($emp != null) { //process this record $emp = }//end while $statement->closeCursor(); The sample code first does a priming fetch, assigning the record data to a variable (note $emp is singular) As long as the record is not null, the code processes the record, then fetches the next record Note the closeCursor method is not called all records have been fetched. If you plan your application properly, most queries won’t return a lot of data. fetchAll makes returning the data to the control very easy. Fetch and display one record at a time Using Parameter Queries Though prepared statements work well with simple queries, their real value comes when you use them for parameter queries SQL Injection attacks avoided To create parameter queries, you must : first define a query that includes parameters prepare the query bind program variables to parameters execute the Parameters come in two flavors: named and unnamed(aka question mark parameters) We’ll start with named parameters $city = 'Stevens Point'; $myQuery = 'Select * From tblStudents ' . 'Where city = :city ' . 'Order By LastName, FirstName'; $statement = $db->prepare($myQuery); $statement->bindValue(':city', $city); $statement->execute();
Unit%206%20-%20MVC%20Database%20Access.docx