php mysql查询和foreach在函数内部不起作用;但外部功能相同的代码工作

时间:2013-08-02 12:16:06

标签: php mysql function foreach

这里是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();

调用该函数

在输出中只获得单词:来自$something的测试。并且vatRates();之后的PHP代码不会执行。

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

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

5 个答案:

答案 0 :(得分: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]);
   }

}

答案 1 :(得分: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目前超出了你的功能的可见性,这将它传递给函数。

答案 2 :(得分: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);

答案 3 :(得分: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*/

 }

答案 4 :(得分:0)

您可能无法正确访问数组中的值。尝试将foreach更改为此

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