Jump to content

How to Run While() Loops with Prepared Statements?


Gimple

Recommended Posts

Hi,

 

With Jacques1's MAJOR help I've been updating my code and changing all queries to run with prepared statements.

 

But it looks like I've run into what will probably be my last problem before this project is complete.

 

After I query my database, how do I run a while() loop to return the data?

 

Here's what I've got, and it's not working:

$prospects = $conn->prepare("SELECT * FROM prospects
WHERE decline=:decline");

$prospects->execute([
	'decline' => false
]);

while($prospect = $prospects->fetchAll()){	
	//code
}

I've also tried just fetch(), but no go.

 

Do you know why this isn't work and how I can fix it?

Link to comment
Share on other sites

Never mind. I should have Googled before asking.

 

I just realized I needed to use a foreach() loop instead of a while().

 

EDIT: By the way, I've looked but can't seem to find where I change the thread to "Answered".

 

How do I do that?

Link to comment
Share on other sites

Just FYI, you can still use a while loop, you just use the fetch method, not fetchAll.

 

while ($row = $stmt->fetch()){
   //...
}
A foreach loop is nicer though so stick with doing it that way.
Link to comment
Share on other sites

You actually don't have to convert all queries to prepared statements. If the query only uses static values, just include them directly in the query string:

$prospects = $conn->query('
    SELECT
        *    -- select specific columns, not just everything
    FROM
        prospects
    WHERE
        NOT decline    -- no need for any external value
');

foreach ($prospects as $prospect)
{
    // ...
}

Prepared statements are only useful if

  • there are dynamic values (e. g. user input)
  • you want to execute the query multiple times during script execution
Link to comment
Share on other sites

I was so set on making my site secure

 

 

Don't forget the most basic of security. Here are a few things you need to be using.

 

Use SSL

X-Content-Type-Options
X-Frame-Options
X-XSS-Protection
X-CONTENT-SECURITY-POLICY
Secure cookie with HttpOnly
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.