Home > Article > Backend Development > How to Iterate Through an Array Multiple Times After Migrating from MySQL to PDO?
Moving from MySQL to PDO: Preserving Array Pointer
PDO offers a different approach to fetching data compared to MySQL's mysql_data_seek() method. To effectively iterate through an array multiple times, follow these steps:
Save Results to an Array:
Instead of relying on the PDO statement directly, save the results to an array using the fetchAll() method. This allows you to work with the array in a more controlled manner.
Code:
<code class="php">$pdo = new PDO('mysql:host=' . $host . ';dbname='.$database, $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('SELECT * FROM mytable WHERE active = 1 ORDER BY name ASC'); $stmt->setFetchMode(PDO::FETCH_ASSOC); $stmt->execute(); $rows = $stmt->fetchAll();</code>
Iterate with Foreach Loop:
Now, you can iterate through the array as many times as needed using foreach loops. This approach enables you to start each iteration from the first element in the array.
Code:
<code class="php">foreach ($rows as $r) { // First iteration } foreach ($rows as $r) { // Second iteration }</code>
Example:
Suppose you have an array of names stored in $rows. The following code demonstrates how to iterate through it twice:
<code class="php">foreach ($rows as $name) { echo $name . "<br>"; // First run: Display all names vertically } foreach ($rows as $name) { echo $name . " "; // Second run: Display all names horizontally }</code>
Advantages:
The above is the detailed content of How to Iterate Through an Array Multiple Times After Migrating from MySQL to PDO?. For more information, please follow other related articles on the PHP Chinese website!