Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through a MySQL query via PDO in PHP?

Tags:

php

mysql

pdo

I'm slowly moving all of my LAMP websites from mysql_ functions to PDO functions and I've hit my first brick wall. I don't know how to loop through results with a parameter. I am fine with the following:

foreach ($database->query("SELECT * FROM widgets") as $results) {    echo $results["widget_name"]; } 

However if I want to do something like this:

foreach ($database->query("SELECT * FROM widgets WHERE something='something else'") as $results) {    echo $results["widget_name"]; } 

Obviously the 'something else' will be dynamic.

like image 629
Andrew G. Johnson Avatar asked Oct 01 '08 21:10

Andrew G. Johnson


People also ask

Which function is used to execute the query in PDO?

To prepare and execute a single SQL statement that accepts no input parameters, use the PDO::exec or PDO::query method.

What is PDO query in PHP?

PDO::query() prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object.

Which PDO method is used to prepare a statement for execution?

Description ¶ Prepares an SQL statement to be executed by the PDOStatement::execute() method. The statement template can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed.


2 Answers

Here is an example for using PDO to connect to a DB, to tell it to throw Exceptions instead of php errors (will help with your debugging), and using parameterised statements instead of substituting dynamic values into the query yourself (highly recommended):

// connect to PDO $pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password");  // the following tells PDO we want it to throw Exceptions for every error. // this is far more useful than the default mode of throwing php errors $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  // prepare the statement. the placeholders allow PDO to handle substituting // the values, which also prevents SQL injection $stmt = $pdo->prepare("SELECT * FROM product WHERE productTypeId=:productTypeId AND brand=:brand");  // bind the parameters $stmt->bindValue(":productTypeId", 6); $stmt->bindValue(":brand", "Slurm");  // initialise an array for the results $products = array(); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {     $products[] = $row; } 
like image 117
Shabbyrobe Avatar answered Sep 18 '22 13:09

Shabbyrobe


According to the PHP documentation is says you should be able to to do the following:

$sql = "SELECT * FROM widgets WHERE something='something else'"; foreach ($database->query($sql) as $row) {    echo $row["widget_name"]; } 
like image 31
Darryl Hein Avatar answered Sep 16 '22 13:09

Darryl Hein