tags:

views:

1103

answers:

2

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.

+2  A: 

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 $results)
{
   echo $results["widget_name"];
}

I'm no expert, but this should work.

Darryl Hein
This doesn't take care of escaping the 'something else' which could be dynamic. Prepared queries as illustrated by Shabbyrobe is the answer.
DGM
@DGB, Darryl's 'something else' from from the original question's example. The question has nothing to do with dynamically assembling queries, it has to do with iterating over the results of a query. Which he answered correctly. Though I agree that Shabbyrobe gave a *better* answer.
Evan Teran
yup, this is definitely correct, and shorter.
andyk
+12  A: 

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):

// $attrs is optional, this demonstrates using persistent connections,
// the equivalent of mysql_pconnect
$attrs = array(PDO::ATTR_PERSISTENT => true);

// connect to PDO
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password", $attrs);

// 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 place holders 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();
if ($stmt->execute()) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $products[] = $row;
    }
}

// set PDO to null in order to close the connection
$pdo = null;
Shabbyrobe
Wow didn't realize someone actually answered this for me, got a +rep and checked it out and low and behold
Andrew G. Johnson