#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    5
    Rep Power
    0

    Couldn't fetch mysqli


    I'm working on a project for a PHP course. Part of the project is to have a chat room where you can challenge other online players to a game. I have a page that is calling some functions from a library in order to access my database tables of users and chat messages.

    Something is going wrong with my query to get all of the online players from the database. My page shows this error:

    Code:
    Warning: mysqli::prepare(): Couldn't fetch mysqli in gameBizData.php on line 140
    Here is the chat room page (I know it's kind of hodge-podgy, I'm planning on cleaning it up later):

    PHP Code:
    <?php
        session_start
    ();
        
        require_once(
    'NMM_Lib.php');
         require_once(
    'Page.class.php');
        require_once(
    './svcLayer/game/gameSvc.php');
        
        
    //if not logged in, re-direct to login.php
        
    if(!isset($_SESSION['userID'])) {
            
    header("Location:login.php");
            exit;
        } else {
            if(isset(
    $_POST['logout'])) {
                
    logout($_POST['user_token'] . "|" $_SESSION['userName']);
                unset(
    $_SESSION['userID']);
                unset(
    $_SESSION['userName']);
                unset(
    $_SESSION['user_token']);
                
    header("Location:login.php");
                exit;
            } else {
                
    $token sha1(uniqid(mt_rand(), true));
                unset(
    $_SESSION['user_token']);
                
    $_SESSION['user_token'] = $token;
            }
            
        }
        
        
    $chats getChats($_SESSION['user_token']);
        
        
    header("Content-Type:text/html");
        echo 
    Page::html_header("Chat");
        
        echo 
    "<div id='chatroom'>";
        echo 
    "<div id='chatbox'>";
        
    $chatsDecoded json_decode($chatstrue);
        foreach(
    $chatsDecoded as $chat) {
            
    $name $chat['name'];
            
    $message $chat['message'];
            echo 
    "<span class='chatName' style='font-weight:bold;'>" $name ": </span><span class='chatMessage'>" $message "</span><br/>";
        }
        echo 
    "</div>";
        
        echo 
    "<div id='onlinePlayers'>";
        
        
    $onlinePlayers getOnlinePlayers($_SESSION['user_token']);
        
        foreach(
    $onlinePlayers as $player) {
            
    $name $player['username'];
            echo 
    "<span class='onlinePlayerName'>" $name "</span>";
        }
        echo 
    "</div>";
        
        echo 
    chatMessageForm();
        echo 
    "</div>";
        
        echo 
    chatJqueryStuff();
        
        echo 
    Page::footer();
    ?>
    The getChats() and getOnlinePlayers() function calls go to gameSvc.php which just checks for a correct token and calls corresponding functions in gameBizData.php, where the database is queried. Here are those functions:

    PHP Code:
    function getChatsData($t) {
        global 
    $mysqli;
        
        if(
    $t === $_SESSION['user_token']) {
            
    $sql "SELECT name, message FROM nmm_chat";
            try {
                if(
    $stmt=$mysqli->prepare($sql)) {
                    
    $chats returnJson($stmt);
                    
    $stmt->close();
                    
    $mysqli->close();
                    return 
    $chats;
                } else {
                    throw new 
    Exception("An error occurred while getting the chat");
                }
            } catch (
    Exception $e) {
                
    log_error($e$sqlnull);
                return 
    false;
            }
        } else {
            return 
    'gameBizData token does not match';
        }
    }

    function 
    getOnlinePlayersData($t) {
        global 
    $mysqli;
        
        if(
    $t === $_SESSION['user_token']) {
            
    $online 1;
            
            
    $sql "SELECT username FROM nmm_user WHERE online=?";
            try {
                if(
    $stmt=$mysqli->prepare($sql)) {
                    
    $stmt->bind_param("i",$online);
                    
    $players returnJson($stmt);
                    
    $stmt->close();
                    
    $mysqli->close();
                    return 
    $players;
                } else {
                    throw new 
    Exception("An error occurred while getting the online players");
                }
            } catch(
    Exception $e) {
                
    log_error($e$sqlnull);
                return 
    false;
            }
        } else {
            return 
    'gameBizData token does not match';
        }

    The returnJson() function is one that the professor provided, and I'm not really sure how it does what it does. It looks like this:

    PHP Code:
    function returnJson ($stmt){
        
    $stmt->execute();
        
    $stmt->store_result();
         
    $meta $stmt->result_metadata();
        
    $bindVarsArray = array();
        
    //using the stmt, get it's metadata (so we can get the name of the name=val pair for the associate array)!
        
    while ($column $meta->fetch_field()) {
            
    $bindVarsArray[] = &$results[$column->name];
        }
        
    //bind it!
        
    call_user_func_array(array($stmt'bind_result'), $bindVarsArray);
        
    //now, go through each row returned,
        
    while($stmt->fetch()) {
            
    $clone = array();
            foreach (
    $results as $k => $v) {
                
    $clone[$k] = $v;
            }
            
    $data[] = $clone;
        }
        
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        
    header("Last-Modified: " gmdate("D, d M Y H:i:s") . " GMT");
        
    header("Cache-Control: no-store, no-cache, must-revalidate");
        
    header("Cache-Control: post-check=0, pre-check=0"false);
        
    header("Pragma: no-cache");
        
    //MUST change the content-type
        
    header("Content-Type:text/plain");
        
    // This will become the response value for the XMLHttpRequest object
        
    return json_encode($data);

    The getChatsData() function is working fine. It's the getOnlinePlayersData() one that isn't working.
    Any input on why I'm getting this error would be appreciated.
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Hi,

    it probably has to do with your functions closing the database connection in the middle of the script. Then of course it can no longer be used in the rest of the script. Why are you doing this?
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    5
    Rep Power
    0
    I was basing my functions off of some other functions the professor provided. I guess I misinterpreted what he was doing. It works now, so thanks!

IMN logo majestic logo threadwatch logo seochat tools logo