[英]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. 这将输出第一行,但是会输出以下
Warning: pg_fetch_row() expects parameter 1 to be resource, boolean given
如果我尝试检索多个行Warning: pg_fetch_row() expects parameter 1 to be resource, boolean given
则为Warning: pg_fetch_row() expects parameter 1 to be resource, boolean given
。 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))
我不明白如何给参数1赋予布尔值,这是第46行的代码在其中出现错误:
($row = pg_fetch_row($result))
Thanks in advance 提前致谢
You can use $row =pg_fetch_array($result)
and then $row['field_name']
to take values out in the foreach loop. 您可以使用
$row =pg_fetch_array($result)
,然后使用$row['field_name']
在foreach循环中取出值。
The error may be because your connection variable $conn
does not connect to your database. 该错误可能是因为您的连接变量
$conn
没有连接到您的数据库。
Try all possibilities. 尝试所有可能性。 Thank you.
谢谢。
If your query fails, pg_query
returns FALSE
. 如果查询失败,
pg_query
返回FALSE
。 Also, you should use pg_query_params
instead to prevent SQL injection. 另外,应该使用
pg_query_params
来防止SQL注入。
Have a look at the examples in the PHP doc: http://php.net/manual/en/function.pg-query.php . 看一下PHP文档中的示例: http : //php.net/manual/en/function.pg-query.php 。
REMEMBER TO: 记得:
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. 通常,在处理PHP-api的细节时,PHP文档是个不错的地方,有时这些细节……可能不那么直观。 :-)
:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.