TomRaikes
TomRaikes

Reputation: 340

How to return results from a database in a PHP foreach loop

So I have this code:

foreach ($_SESSION['basket'] as $item) {
    $ref = $_SESSION['basket'][$counter];

    $result = pg_query ($conn, 'SELECT * from music WHERE ref='.$ref.' ORDER BY artist');
}

This will output the first row fine, however it outputs this Warning: pg_fetch_row() expects parameter 1 to be resource, boolean given if I try to retrieve more than one row. I don't understand how I'm giving a boolean to parameter 1, this is the code on line 46 where it is getting the error: ($row = pg_fetch_row($result))

Thanks in advance

Upvotes: 0

Views: 850

Answers (3)

Ataboy Josef
Ataboy Josef

Reputation: 2101

You can use $row =pg_fetch_array($result) and then $row['field_name'] to take values out in the foreach loop.

The error may be because your connection variable $conn does not connect to your database.

Try all possibilities. Thank you.

Upvotes: 1

Michael Valentin
Michael Valentin

Reputation: 56

Have a look at the examples in the PHP doc: http://php.net/manual/en/function.pg-query.php.

REMEMBER TO:

  • A: Escape input, or even better use prepared statements
  • B: Check the return value before iterating over the results. If an error occured it doesn't make sense to try and iterate.

In general the PHP docs are a great place, when strugling with the details of the PHP-api's, which are sometimes... Less intuitive than they could be. :-)

Upvotes: 0

tsnorri
tsnorri

Reputation: 2097

If your query fails, pg_query returns FALSE. Also, you should use pg_query_params instead to prevent SQL injection.

Upvotes: 0

Related Questions