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?

Edited by Gimple
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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.