Watashi
Watashi

Reputation: 13

Using variables outside the function

this is probebly a silly question but I don't know where else to ask this. I need to call on $conn in the functions below, but if I try to turn it into a global it doesn't work. If someone can explain to me how to use an outside variable inside a function I'd be very grateful.

Here's my little piece of code:

<?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();

?>

Upvotes: 0

Views: 52

Answers (2)

Rasclatt
Rasclatt

Reputation: 12505

I personally would try 1) to create a connection class that has a static connection (basically a global without being a global) that allows you to create instances both inside and outside of functions. Also, if you make it a singleton, you can reuse the same connection without anymore resources 2) Make one function that can handle more than one insert. Below is just an example, use or don't use it, but it will give you a simple example, by no means is it complete, so use at your own risk:

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);

Upvotes: 1

Wee Zel
Wee Zel

Reputation: 1324

don't use globals unless you REALLY have to! don't forget to pass your $conn parameter to your functions e.g.

change this:

insert_twice();

to this:

insert_twice($conn);

I'd suggest adding some error handling to your mysql_query() calls too, you should not assume that these are always successful

Upvotes: 1

Related Questions