2015-02-24 163 views
0

我確定這個問題很容易回答,但我不明白。 當我嘗試連接一個函數時,它會拋出一個「訪問被拒絕用戶'@'localhost'」錯誤。它看起來像數組在數組中不可用,因爲錯誤說我沒有輸入用戶名和密碼。mysqli_connect函數拋出錯誤

的代碼是:

$config["mysql_host"] = "localhost"; 
$config["mysql_user"] = "myusername"; 
$config["mysql_pass"] = "mypass"; 
$config["db_name"]  = "mydb_name"; 
$config["event_tname"] = "tablename"; 


function get_events(){ 
     $mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database 

     $sql = "SELECT * FROM ".$config["event_tname"]; //a simple query 

     $result = mysqli_query($mysqli, $sql) or die ("Error, please contact the provider!"/* . mysqli_error()*/); //execute 

     while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it 
      foreach($all_events as $key => $val) 
       echo($val." | "); 
     } 

     mysqli_free_result($result);} //END -- clear $result 
events(); //just an example: call the function 

我有什麼在陣列,以改變?

問候, 弗朗茨

+1

http://php.net/manual/zh/language.variables.scope.php – 2015-02-24 19:46:34

回答

0

首先,你應該考慮使用的mysqli對象爲導向。沒有理由再使用程序風格。

其次,全局PHP變量在函數內部不可用,因此您需要將數組傳遞給函數,如其他答案中所述。

有關PHP變量作用域的更多信息,請參閱this article

Imho最好的解決方案是爲您的應用程序使用類並將配置存儲爲私有屬性。那個類的方法就可以訪問屬性。

0

只是自己的函數中添加global $config;作爲

function get_events(){ 

    global $config; 

     $mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database 

     $sql = "SELECT * FROM ".$config["event_tname"]; //a simple query 

     $result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error()); 

     while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it 
      foreach($all_events as $key => $val) 
       echo($val." | "); 
     } 

     mysqli_free_result($result);} //END -- clear $result 
get_events(); //ju 

或通過配置參數去功能

function get_events($config){ 

     $mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database 

     $sql = "SELECT * FROM ".$config["event_tname"]; //a simple query 

     $result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error()); 

     while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it 
      foreach($all_events as $key => $val) 
       echo($val." | "); 
     } 

     mysqli_free_result($result);} //END -- clear $result 
get_events($config); //ju 
+0

Omg,對於這個問題抱歉: :D謝謝^^ – Franz 2015-02-24 20:39:30