简体   繁体   English

如何在PHP foreach循环中从数据库返回结果

[英]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: 记得:

  • A: Escape input, or even better use prepared statements 答:转义输入,甚至更好地使用准备好的语句
  • B: Check the return value before iterating over the results. B:在遍历结果之前检查返回值。 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. 通常,在处理PHP-api的细节时,PHP文档是个不错的地方,有时这些细节……可能不那么直观。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM