Home  >  Article  >  Database  >  How to Loop Through MySQL Query Results with PDO and Parameters?

How to Loop Through MySQL Query Results with PDO and Parameters?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 00:24:03640browse

How to Loop Through MySQL Query Results with PDO and Parameters?

Looping Through MySQL Query Results with PDO

Query with Parameter

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:

  1. Prepare a parameterized statement using the prepare() method. This places placeholders in the query where dynamic values will be substituted.
  2. Bind values to the placeholders using the bindValue() method.
  3. Execute the statement using the execute() method.
  4. Fetch the results using the fetch() method.

Example

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn