PDO Cursor

The PDO data layer in PHP allows us standard database management. In this example we are going to see how to handle a DPO cursor. A PDO cursor will be the set of data resulting from executing a statement.

The first thing we will do in PDO is connect to our database. In this case it will be a MYSQL database, hence the connection string. The connection will be achieved by instantiating the PDO object.

$db = new PDO('mysql:host=localhost;dbname=codeline;charset=utf8mb4', 'user', 'password');

The PDO object receives the connection string followed by the connection user/password.

Now we will proceed to execute the statement that the PDO cursor returns. To execute the statement we use the query() method.

$db->query('SQL STATEMENT')

In this case we will pull on a table of users.

$db->query('SELECT first_name,last_name FROM users')

Executing the query() method will return the PDO cursor. So we will use a foreach structure to be able to iterate through it.

foreach($db->query('SELECT first_name,last_name FROM users') as $row) { ... }

In each iteration we will have the cursor data row in the $row object. So we can access a specific column through the statement.

$row['column_name']

The final code would look like this:

foreach($db->query('SELECT first_name,last_name FROM users') as $row) {
  echo $row['first_name'].' '.$row['last_name'].'
';
}

We must not forget to control the errors that may appear during the execution of the program, so it is good that we integrate everything using a try-catch loop that controls the PDOException exception.

And with this we have already managed to create our program that manages and cycles through a PDO cursor.