简体   繁体   English

在函数内运行查询

[英]Run query inside a function

I have searched everywhere without behing able to figure out the right way forward. 我到处搜寻,却找不到正确的前进方向。

In my controller.php I have: 在我的controller.php中,我有:

<?php $get_listing = function ($id) {
$results = $db->query("SELECT * FROM listings ORDER BY date DESC");
$listings = $results->fetchAll(PDO::FETCH_ASSOC);
} ?>

Above is my function for retrieving data from the database. 上面是我从数据库检索数据的功能。 I want to retrieve a specific row based on the variable $id. 我想基于变量$ id检索特定行。

Now, in my ad-details.php, I have: 现在,在我的ad-details.php中,我有:

<?php foreach(get_listing($id) as $info) {
echo $info["price"]; }

I get an error message saying that the function get_listing is undefined, which is strange because the controller.php is included in the ad-details.php 我收到一条错误消息,说函数get_listing是未定义的,这很奇怪,因为controller.php已包含在ad-details.php中

Any ideas guys? 有想法吗? Any help would be highly appreciated. 任何帮助将不胜感激。

2 errors: 2个错误:

1 - You forgot 1-你忘了

global $db;

and the return statement in your function. 以及函数中的return语句。

2 - If you use anonymous functions , you need to call them with $ sign. 2-如果使用匿名函数 ,则需要使用$符号来调用它们。 Probably 大概

<?php 
   foreach($get_listing($id) as $info) {
       echo $info["price"]; 
   }
?>

is working. 正在工作。

You've set your function to a variable named $get_listing , but call it with get_listing . 您已将函数设置为名为$get_listing的变量,但使用get_listing调用。

Either declare your function like this. 要么这样声明您的函数。

function get_listing($id)

Or call it like this. 或这样称呼它。

$get_listing($id)
<?php
function get_listing($id)
  {
    $results  = $db->query("SELECT * FROM listings ORDER BY date DESC");
    $listings = $results->fetchAll(PDO::FETCH_ASSOC);
  }
?>

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

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