0
/*connection file*/
    function connect(){
            $server = "localhost";
            $user = "xxxx";
            $password = "xxxx";
            $db = "xxxx";
            $connetion = mysqli_connect($server,$user,$password,$db);
    }

This is my connection file. i am connect to database using MVC.

/*function declaration and insert query*/
    function insert($table,$value){ 
        $fld = "";
        $val = "";
        $i = 0;
        foreach ($value as $k => $v) {
            if($i == 0){
                $fld .= $k;
                $val .= "'" . $v ."'";
            }
            else{
                $fld .= "," . $k;
                $val .= ",'" .$v . "'";
            }
            $i++;
        }
        global $conn;
        return mysqli_query($conn,"INSERT INTO $table($fld) VALUES($val)") or die(mysqli_error($conn));
    }

It is gives warning when i am trying to insert data into database.

Please help me for solve this warning.

Shah Ankit
  • 119
  • 2
  • 4
  • 16
  • Would like to see how did you extend your connection file – Vicky Gonsalves Feb 11 '16 at 05:00
  • include_once './connection.php'; i extends my connection file as like this. – Shah Ankit Feb 11 '16 at 05:02
  • you need to use return statement. and store it somewhere in $conn variable, – Amit Shah Feb 11 '16 at 05:03
  • Your `function connect()` creates a connection, but since it does not return the connection, it is out of scope. You need to append `return $connection;` in the function, and then when you do `$conn = connect();` you will have the returned connection – Sean Feb 11 '16 at 05:04

2 Answers2

1

You need to return $connection so that it will not be undefined in global $connection;:

function connect(){
    $server = "localhost";
    $user = "xxxx";
    $password = "xxxx";
    $db = "xxxx";
    $connection = mysqli_connect($server,$user,$password,$db);
    return $connection; // return $connection
}

Note: You spelled $connection wrongly, should not be $connetion.

Panda
  • 6,955
  • 6
  • 40
  • 55
0

You need to return connection object from the function connect.

function connect(){
        $server = "localhost";
        $user = "xxxx";
        $password = "xxxx";
        $db = "xxxx";
        $connection = mysqli_connect($server,$user,$password,$db);
        return $connection; // return connection object
}
Samir Selia
  • 7,007
  • 2
  • 11
  • 30