When using PDO to query a database, you may encounter the need to execute queries with dynamic parameters. This allows you to easily query data based on user input or other runtime variables.
To loop through results with a parameter, use the following steps:
<code class="php">$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare("SELECT * FROM widgets WHERE something=:something"); $stmt->bindValue(":something", "something else"); $stmt->execute(); while ($results = $stmt->fetch(PDO::FETCH_ASSOC)) { echo $results["widget_name"]; }</code>
In this example, the $something placeholder in the query is bound using the bindValue() method, and the results are then fetched using the fetch() method within a loop.
The above is the detailed content of How to Loop Through MySQL Query Results with PDO and Parameters?. For more information, please follow other related articles on the PHP Chinese website!