0

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.

Edited by pritaeas: Moved to PHP.

3
Contributors
7
Replies
47
Views
2 Years
Discussion Span
Last Post by matrixdevuk
0
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.

0

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'];
        }
    }
0

@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

1

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.

Edited by diafol

1

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'];
        }
    }

Edited by matrixdevuk: lowercase -> UPPERCASE

0

@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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.