1

I have a function in function.php which outputs okay when calling inside the file, but if I include function.php in another file and call the function I get error.

Here is my function.php

    $mysqli = new mysqli('localhost','dbuser','dbpassword','dbname');

    if( $mysqli->connect_error ) {
       die('Connect Error (' . $mysqli->connect_errno . ') '
                . $mysqli->connect_error);
         mysqli_set_charset($mysqli,"utf8");  
    } 
    $date=$mysqli->real_escape_string($_GET["date"]);
    if(!empty($date)) {
        $date = $mysqli->real_escape_string($_GET['date']);
    } else {
        $date = date("Y-m-d", strtotime('today'));  
    }

    function functionname() {
        global $mysqli, $date;
        $sql=mysqli_query($mysqli,"SELECT * FROM database WHERE DateLT= '".$date."'");
        if(mysqli_num_rows($sql) > 0) {
            echo "somedata";
            while($row = mysqli_fetch_array($sql))
            {

                echo "somedata";
            }
        } else {

        }
    }
    functionname()
    $mysqli->close();
/*-->*/

Output okay. But if i call function from example.php like this,

<?php define('ROOT', $_SERVER['DOCUMENT_ROOT']);

include(ROOT."/function/function.php");  

functionname();?> 

I get mysqli error.

10
  • 3
    What's the error you're getting? Commented May 11, 2017 at 18:32
  • mysqli_query(): Couldn't fetch mysqli Commented May 11, 2017 at 18:37
  • Tip: you should get used to preparing your statements beforehand, your current code is vulnerable to injection. Have you checked the database connection if it's working? Commented May 11, 2017 at 18:57
  • database working Commented May 11, 2017 at 18:59
  • 1
    Do you call mysqli_close($mysqli) anywhere? If you close the connection and then try to call funcctionname() you'll get that error. Commented May 11, 2017 at 19:04

1 Answer 1

3

The problem is that you do

$mysqli->close();

at the end of function.php. You can't use the connection after you've closed it.

Take out that line.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.