在函数外部使用变量

时间:2015-07-26 13:07:34

标签: php function variables

这可疑是一个愚蠢的问题,但我不知道还能在哪里问这个问题。 我需要在下面的函数中调用$ conn,但如果我尝试将其转换为全局函数则不起作用。如果有人能向我解释如何在函数中使用外部变量,我将非常感激。

这是我的一小段代码:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
 //Maak connectie met database
 $host = "localhost";
 $username = "i266161_studie";
 $password = "studie";
 $dbnaam = "test";
 $fout = "Error: Failed to open database";

 $conn = mysqli_connect($host, $username, $password, $dbnaam)
 or die ("Connection failed: ".mysqli_connect_error()); 

function insert_once($conn){
$query = 'INSERT INTO gebruikers (naam, leeftijd, woonplaats)
VALUES ("Henk", 17, "Eindhoven")';
mysqli_query($conn,$query);
}

function insert_twice($conn){
$query = 'INSERT INTO gebruikers (naam, leeftijd, woonplaats)
VALUES ("Bert", 21, "Helmond"), ("Ruud", 32, "Helmond")';
mysqli_query($conn,$query);
}
insert_twice();

?>

2 个答案:

答案 0 :(得分:1)

除非你真的需要,否则不要使用全局变量!不要忘记将$conn参数传递给您的函数,例如

改变这个:

insert_twice();

到此:

insert_twice($conn);

我建议您为mysql_query()电话添加一些错误处理,您不应该认为这些错误处理总是成功

答案 1 :(得分:1)

我个人会尝试1)创建一个具有静态连接的连接类(基本上是一个全局而不是global),它允许您在函数内部和外部创建实例。此外,如果你使它成为一个单独的,你可以重新使用相同的连接而不再有资源2)创建一个可以处理多个插入的函数。以下只是一个示例,使用或不使用它,但它会给你一个简单的例子,绝不是完整的,所以使用风险自负:

<强> interface.Database.php

interface   Database
    {   
        public  static  function SetConnection($host,$username,$password,$dbnaam);
    }

<强> class.MySQLConn.php

class   MySQLConn implements Database
    {           
        protected   static  $host;
        protected   static  $username;
        protected   static  $password;
        protected   static  $dbnaam;

        public      static $connect;

        private function __construct()
            {
            }

        public  static  function SetConnection($host = "localhost",$username = "i266161_studie",$password = "studie",$dbnaam = "test")
            {
                self::$host     =   $host;
                self::$username =   $username;
                self::$password =   $password;
                self::$dbnaam   =   $dbnaam;
                self::$connect  =   (!isset(self::$connect))? self::Initialize() : self::$connect;
            }

        private static  function Initialize()
            {
                return new mysqli(self::$host, self::$username, self::$password, self::$dbnaam);
            }
    }

<强> function.insert_into.php

// Make your insert a bit more robust
// Should be built out to accommodate preparing and binding
// This will handle one or multiple row insert
function insert_to($settings = false)
    {
        $con    =   MySQLConn::$connect;

        $table  =   (isset($settings['table']))? $settings['table']:"gebruikers";
        $cols   =   (isset($settings['cols']) && is_array($settings['cols']))? "(`".implode("`,`",$settings['cols'])."`)":false;

if($cols == false)
    return false;

if(is_array($settings['vals']) && !empty($settings['vals'])) {
        foreach($settings['vals'] as $values) {
                $sql[]  =   "('".implode("','",$values)."')";
            }

        return $con->query("INSERT INTO {$table} {$cols} VALUES ".implode(",",$sql));

    }
}

<强>的index.php

// Include assets
include_once('interface.Database.php');
include_once('class.MySQLConn.php');
include_once('function.insert_into.php');

// Create instance and initialize connection
MySQLConn::SetConnection();

// create settings (you could get them from posts)
// You have to sanitize user input or as mentioned bind/prepare values    
$query["cols"]      =   array("naam","leeftijd","woonplaats");
$query["table"]     =   "gebruikers";
$query["vals"][]    =   array("Henk", 17, "Eindhoven");
$query["vals"][]    =   array("Ruud", 32, "Helmond");

insert_into($query);