0

这里php函数

(阅读评论等后更新)

是的,$db在函数之外定义

$db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8", $dbuser, $dbpass//, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

function vatRates () {
   $something = "test";
   echo $something;

try {
   $query_select_date = "SELECT CurrencyRate FROM 2013Currencies WHERE DateOfCurrencyRate = '2001-03-23'";

   $sql_select_date = $db->prepare($query_select_date);
   $sql_select_date->execute();
   $data_select_date = $sql_select_date->fetchAll(PDO::FETCH_ASSOC);
   }
 catch (PDOException $e){
 echo "<br>DataBase Error: " .$e->getMessage();
 }
 catch (Exception $e) {
 echo "General Error: ".$e->getMessage() .'<br>';
 }

   foreach ($data_select_date as $data) {
       echo($data[CurrencyRate]);
   }


}

然后调用函数vatRates();

在输出中只得到一个词:test from $something。并且之后的php代码vatRates();不会执行。

但是如果删除function vatRates () {并关闭,}那么 mysql 查询和 foreach 就可以工作。

为什么mysql查询和foreach在函数内部不起作用(需要纠正什么)?

4

5 回答 5

2
function vatRates () {
   global $db;
   $something = "test";
   echo $something;

   $query_select_date = "SELECT CurrencyRate FROM 2013Currencies WHERE DateOfCurrencyRate = '2001-03-23'";

   $sql_select_date = $db->prepare($query_select_date);
   $sql_select_date->execute();
   $data_select_date = $sql_select_date->fetchAll(PDO::FETCH_ASSOC);

   foreach ($data_select_date as $data) {
       echo($data[CurrencyRate]);
   }

}
于 2013-08-02T12:19:27.553 回答
2
function vatRates ($db) {
   $something = "test";
   echo $something;

   $query_select_date = "SELECT CurrencyRate FROM 2013Currencies WHERE DateOfCurrencyRate = '2001-03-23'";

   $sql_select_date = $db->prepare($query_select_date);
   $sql_select_date->execute();
   $data_select_date = $sql_select_date->fetchAll(PDO::FETCH_ASSOC);

   foreach ($data_select_date as $data) {
       echo($data[CurrencyRate]);
   }

}

用 vatRates($db) 调用

原因:$db 当前不在您的函数的可见性范围内,这会将其传递给函数。

于 2013-08-02T12:20:13.937 回答
2

函数必须返回一些东西,一个字符串,一个数组,一个布尔值等。

更好的是(通过 arg $db):

function vatRates ($db) {
$CurrencyRate = "";

$query_select_date = "SELECT CurrencyRate FROM 2013Currencies WHERE DateOfCurrencyRate = '2001-03-23'";

$sql_select_date = $db->prepare($query_select_date);
$sql_select_date->execute();
$data_select_date = $sql_select_date->fetchAll(PDO::FETCH_ASSOC);

foreach ($data_select_date as $data) {

$CurrencyRate .= $data[CurrencyRate];
}
return $CurrencyRate;
}

要使用它:

echo vatRates($db);
于 2013-08-02T12:20:35.623 回答
1
function vatRates () {
   $something = "test";
   echo $something;
   global $db;

   /* Your sql code and foreach goes here*/

}

或者

function vatRates ($db) {
       $something = "test";
       echo $something;

       /* Your sql code and foreach goes here*/

 }
于 2013-08-02T12:19:09.297 回答
0

可能是您没有正确访问数组中的值的问题。尝试将 foreach 更改为此

foreach ($data_select_date as $data) { 
  echo($data['CurrencyRate']);
}
于 2013-08-02T12:19:15.167 回答