简体   繁体   中英

PDO query not returning results in PHP foreach loop

I have a function (below) which isn't returning a result set from a PDO query inside a foreach loop. Not sure what could be the problem. To explain a bit, I'm running PHP v5.6.3 and the $csv string passed to the function is something like:

$csv = "red, brown, blue";

After the str_getcsv is ran, print_r($colors) works as expected. I've tried preparing the query and binding values inside or outside the loop with no success, and if I pull the query outside of the loop (and run it once) it works.

function generateColors($csv) {
    global $db; // Connect DB
    $colors = str_getcsv($csv, ","); //Converts the CSV to an array
    $query = $db->prepare("SELECT * FROM colors WHERE slug = :slug");
    foreach ($colors as $slug) {
        $query->bindValue(':slug', $slug, PDO::PARAM_STR);
        $query->execute();
        $result = $query->fetch(PDO::FETCH_ASSOC);
        echo "COLOR: " .$slug;
        echo "<br>";
        var_dump($result);
    }
}

The output (below) shows that the loop is working, just the query seems to stop returning values after 1 iteration. Any help on why I'm getting a bool(false) instead of an array set like [column 1]=>value 1, [column 2]=>value 2, etc., would be greatly appreciated.

COLOR: red
array -> [column]=>value, [column]=value, etc. // returned as expected.
COLOR: brown
bool(false)
COLOR: blue
bool(false)

You should bind the params inside the foreach. Before the foreach your variable $slug is not defined.

function generateColors($csv) {
    global $db; // Connect DB
    $colors = str_getcsv($csv, ","); //Converts the CSV to an array
    $query = $db->prepare("SELECT * FROM colors WHERE slug = :slug");
    foreach ($colors as $slug) {
        $query->bindValue(':slug', $slug, PDO::PARAM_STR);
        $query->execute();
        $result = $query->fetch(PDO::FETCH_ASSOC);
        echo "COLOR: " .$slug;
        echo "<br>";
        var_dump($result);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM