Hi Everyone, I have the following prepared statement and I am having problems displaying data from my test db
Can someone help me out please.

        $STM = $dbh->prepare('SELECT * FROM tbl WHERE var = :lsecure');
        $STM->bindParam(':lsecure', $var);
        $STM->execute();
        $count = $STM->rowCount();
        $row  = $STM -> fetch();

            if($count > 0){     
                foreach($results as $row);
                    $varname = $row['var']; 
                }

The $var is being displayed from session data and I know it is correct.
Thanks in advance.

Member Avatar for diafol
foreach($results as $row);
    $varname = $row['var']; 
}

$results doesn't exist. You are only fetching one record (fetch). So there are no multiple records for a "for loop" - just the fields of one record.

Please explain what it is you're trying to do.

Not sure if you prefer this, but here's the way I would've done it...

    $STM = $dbh->prepare('SELECT * FROM `tbl` WHERE `var`=:lsecure');
    $STM->execute([ # new syntax for arrays, alternatively, use array()
        ":lsecure" => $var
    ]);
    $count = $STM->rowCount();
    $results = $STM->fetchAll(PDO::FETCH_ASSOC);
    if($count > 0)
    {
        foreach($results as $row);
            $varname = $row['var'];
        }
    }

@diafol & @matrixdevuk- Thanks for replying

@Diafol - I am trying to get all records from the db where lsecure = $var
@matrixdevuk - Thanks, I will give that a go and let you know the results

Sorry for the late reply,
Thanks again

Member Avatar for diafol

OK if you want all records, then you probably need fetchAll as matrixdevuk shows. However this is useful when you don't want to process the data further with php. Although you can use array functions like array_map() etc to do so if you want. Otherwise you use the fetch method in a while loop.

Here's an example with @diafol's while loop idea:

    $STM = $dbh->prepare('SELECT * FROM `tbl` WHERE `var`=:lsecure');
    $STM->execute([ # new syntax for arrays, alternatively, use array()
        ":lsecure" => $var
    ]);
    $count = $STM->rowCount();
    if($count > 0)
    {
        while($row = $STM->fetch(PDO::FETCH_ASSOC));
            $varname = $row['var'];
        }
    }

@diafol & @matrixdevuk- Thanks for replying once again, This is why I love Daniweb, Thanks very much for your help and examples.

They both work great and I can work through pieces of my code and update them to the more secure statements.

Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.