Niels
Niels

Reputation: 425

Notice: Undefined variable: mysqli in... on line 63

I received this error I really don't know what to do about it. I'm tyring to build a 'form' with which you can add information to a database. Because I want no double records in my database i'm checking some fields with AJAX.

Here you see the code of my class where I receive my error from. (I use mysqli - language)

<?php
class Places {

    private $m_sName;
    private $m_sStreet;
    private $m_sHouseNumber;
    private $m_sCity;
    private $m_sCategory;

    public function __set($p_sProperty, $p_vValue) {
        switch($p_sProperty) {
            case "Name" :
                $this -> m_sName = $p_vValue;
                break;
            case "Street" :
                $this -> m_sStreet = $p_vValue;
                break;
            case "HouseNumber" :
                $this -> m_sHouseNumber= $p_vValue;
                break;
            case "City" :
                $this -> m_sCity = $p_vValue;
                break;
            case "Category" :
                $this -> m_sCategory = $p_vValue;
                break;
        }
    }

    public function __get($p_sProperty) {
        $vResult = null;
        switch($p_sProperty) {
            case "Name" :
                $vResult = $this -> m_sName;
                break;
            case "Street" :
                $vResult = $this -> m_sStreet;
                break;
            case "HouseNumber" :
                $vResult = $this -> m_sHouseNumber;
                break;
            case "City" :
                $vResult = $this -> m_sCity;
                break;
            case "Category" :
                $vResult = $this -> m_sCategory;
                break;
        }
        return $vResult;
    }

    public function addPlaces() 
    {
        include_once("connection.php");
            $sSql = "INSERT INTO tblPlaces
                (Name, 
                Street, 
                HouseNumber, 
                City, 
                Category) 
                VALUES 
                ('" . $mysqli -> real_escape_string($this -> m_sName) . "', 
                '" . $mysqli -> real_escape_string($this -> m_sStreet) . "', 
                '" . $mysqli -> real_escape_string($this -> m_sHouseNumber) . "', 
                '" . $mysqli -> real_escape_string($this -> m_sCity) . "', 
                '" . $mysqli -> real_escape_string($this -> m_sCategory) . "')";


        if (!$mysqli -> query($sSql))
        {
            throw new Exception("Er is iets mis gelopen bij het toevoegen van een plaats");
        }

    }

    public function placeAvailable()
    {

        include("connection.php");

        $sSql= "select Street from tblPlaces
                where Street = '".$this->m_sStreet."' AND HouseNumber = '".$this->m_sHouseNumber."'";

        $vResult=$mysqli->query($sSql);
        if($vResult->num_rows>0)
        {

            return(false);  
        }
        else
        {

            return(true);
        }

        $mysqli->close();   
    }
}
?>

In my connection file I have this code:

<?php

$localhost = "localhost";
$user = //user hidden
$password = //paswoord hidden 
$database = //database hidden

$mysqli = new mysqli($localhost, $user, $password,$database);

if ($mysqli->connect_error) {
    throw new Exception("Geen Databankconnectie");
}
?>

Does anyone have a solution? Or do you also want to see my ajax file and .php page? Thanks

EDIT

This is my add.php file (at least everything that matters)

<?php
$feedback = "";
include_once ('assets/classes/places.class.php');
if (isset($_POST['knop'])) {
    try 
    {
        $place1 = new Places;
        $place1 -> Name = $_POST['Name'];
        $place1 -> Street = $_POST['Street'];
        $place1 -> HouseNumber = $_POST['HouseNumber'];
        $place1 -> City = $_POST['City'];
        $place1 -> Category = $_POST['Category'];

            if($place1->placeAvailable())
            {
                $place1 -> addPlaces();
                $feedback = $place1 -> Name . ", is met succes toegevoegd!";
            }
            else
            {
                $feedback = "Sorry";            
            }
    } 
    catch (Exception $e) 
    {
        $feedback = $e -> getMessage();
    }
}

?>
<!DOCTYPE html>
<html lang="en">
    <head>

        <meta charset="utf-8" />
        <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
        Remove this if you use the .htaccess -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>Search | FoodSquare</title>
        <link rel="stylesheet" href="assets/css/reset.css" />
        <link rel="stylesheet" href="assets/css/style.css" />
        <script type="text/javascript" src="assets/javascript/geolocation.js"></script>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

        <meta name="description" content="" />
        <meta name="viewport" content="width=device-width; initial-scale=1.0" />
        <!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
        <link rel="shortcut icon" href="/favicon.ico" />
        <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
            $("#klik").click(function(){
            var naam = $("#naam").val();
            var plaats = $("#straat").val();
            var nummer = $("#huisnummer").val();
            var block = "block";

        $.ajax({
            type: "POST",
            url: "assets/ajax/check_place.php",
            data: { eet:naam, place:plaats, number:nummer }
        }).done(function( msg ) {

            if(msg.status != "error")

                {
                    if(msg.available == "yes")
                    {
                        $(".feedback").fadeOut();
                    }
                    else
                    {
                        $(".feedback span").text(msg.message);
                        $(".feedback").fadeIn();
                        $(".feedback").css("display", block);
                    }
                }

        });
        return(false);

    })

});
</script>
    </head>
    <body>

This is my ajax FILE

<?php
ini_set('display_errors', 1);
    include_once('../classes/places.class.php');
try
{
    $oPlace = new Places();
    $oPlace->Name = $_POST['eet'];
    $oPlace->Street = $_POST['place'];
    $oPlace->HouseNumber = $_POST['number'];
    if($oPlace->placeAvailable())
    {
        $feedback['status'] = "success";
        $feedback['available'] = "yes";
        $feedback["message"] = "Go ahead, street is available";
    }   
    else
    {
        $feedback['status'] = "success";
        $feedback['available'] = "no";
        $feedback["message"] ="De zaak " . "'" . $_POST['eet'] . "'". " is reeds op dit adres gevestigd." ;
    }
}
catch(exception $e)
{
    $feedback['status'] = "error";
    $feedback["message"] =$e->getMessage();

}
header('Content-type: application/json');
echo json_encode($feedback);
?>

Ok guys, I tried several of your solutions but none of them works. I will probably be my fault but I figured something out and i replaced the INCLUDE_ONCE by INCLUDE and now i can add something to my database BUT only without AJAX, when i use AJAX, the form checks if the values are already in the database but when I add them, nothing happens. I also receive no errors. I also receive the right information back from ajax. Can anyone help please? thank you

Upvotes: 0

Views: 22695

Answers (3)

raina77ow
raina77ow

Reputation: 106443

The common solution is to include the file with connection definitions where these connections will actually be used (in other words, in a high-level code) - and not in libraries, where some DB-related functions and classes are defined.

The file itself is usually a singleton class, with both constructor and __clone method made private. Like this:

class DbConnection {
  private static $connection;
  private function __construct() {} // not needed in this example, really, as we only need a connection, which is a stable resource.
  private function __clone() {} // nothing to see here, move on!
  private function __wakeup() {} // ...and I really mean it!
  public static function getConnection() { 
    if (!isset(self::$connection)) { 
      self::$connection = new mysqli(...);
      // and so created was a connection for all creatures, big and small, 
      // to share and enjoy!
    }
    return self::$connection; 
  }
}

Then you can safely use the connection each time you required it by using the...

  $conn = DbConnection::getConnection();

... including that class file just ONCE.

Upvotes: 2

Andreas Stokholm
Andreas Stokholm

Reputation: 1687

A quick and dirty solution is to add global $mysqli in your methods using database access. Like this

    include_once("connection.php");
    global $mysqli;
        $sSql = "INSERT INTO tblPlaces
            (Name, 
            Street, 
            HouseNumber, 
            City, 
            Category) 
            VALUES 
            ('" . $mysqli -> real_escape_string($this -> m_sName) . "', 
            '" . $mysqli -> real_escape_string($this -> m_sStreet) . "', 
            '" . $mysqli -> real_escape_string($this -> m_sHouseNumber) . "', 
            '" . $mysqli -> real_escape_string($this -> m_sCity) . "', 
            '" . $mysqli -> real_escape_string($this -> m_sCategory) . "')";


    if (!$mysqli -> query($sSql))
    {
        throw new Exception("Er is iets mis gelopen bij het toevoegen van een plaats");
    }

}
?>

And by dirty, I mean really dirty! - But the way you've made it will require a pretty huge restructuring if it is to be made otherwise.

Upvotes: 0

John Conde
John Conde

Reputation: 219874

You shouldn't be using an include in your method declaration. That's a bad practice. Start by passing your MySQLi object as a paramter in your constructor:

include_once("connection.php");
$place = new Places($mysqli) {
    $this->mysqli= $mysqli;
}

Then you would use it in your class like this;

$this->mysqli->real_escape_string

instead of

$mysqli->real_escape_string

Upvotes: 2

Related Questions