0

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

Niels
  • 425
  • 5
  • 9
  • 22
  • Did you include the connection file? – Quentin Pradet May 07 '12 at 13:03
  • 2
    Please, PHP devs of the world, bold and not so, never ever use `include/require` in a function definition. And I mean NEVER. – raina77ow May 07 '12 at 13:06
  • @raina77ow Why? Zend Framework uses `include` and `require` all over the place in case the autoloader isn't setup. – Mike B May 07 '12 at 13:18
  • In _function definitions_? Really? With PHP still as it is, an interpreted language? How about showing some code to prove it? – raina77ow May 07 '12 at 13:25
  • Meanwhile, look at this [topic](http://stackoverflow.com/questions/10319398/function-populates-first-listbox-but-not-the-second-from-a-database-table) - to see a fine example of the problems caused by happily throwing require_once instead of restructuring the code. – raina77ow May 07 '12 at 13:28
  • @raina77ow I'm not saying they aren't caveats.. but such is life. grep Zend Framework for non-exception files that are being included and you'll get 4,474 hits.. 99% of them are right before using a new class.. NOT to include scoped variables like the OP is doing. I'm not so much arguing for or against the concept.. just wanted to take issue with the absoluteness of your blanket statement that they should never be used under any circumstance. – Mike B May 07 '12 at 14:15
  • @raina77ow List required/included calls within methods in Zend Framework http://pastebin.com/x5wJCKh5 – Mike B May 07 '12 at 14:22
  • My 'blanket' statement was related to using include and require in _function definitions_. Of course, it's normal to use these statements in the class headers: what made you think I actually advised against it? – raina77ow May 07 '12 at 14:28
  • @raina77ow I'm trying to stay pleasant, no reason to get offended :) – Mike B May 07 '12 at 14:38
  • Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Dharman Jun 09 '20 at 20:59

3 Answers3

2

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
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • To clarify: You're not saying `include` or `require` in a method is bad by itself.. you're saying it's bad because he's trying to use variables and other things from the included file's scope. Including files that contain classes (like exceptions) are very common in frameworks. – Mike B May 07 '12 at 13:26
  • 1
    Well, 'like exceptions' is a bold statement, because no common class is usually exception-like (stopping the program's flow, that is). Still, I'd never want to touch a code which has includes hidden within its logic. – raina77ow May 07 '12 at 13:35
2

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.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • 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? – Niels May 07 '12 at 15:22
0

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.

Andreas Stokholm
  • 1,677
  • 1
  • 12
  • 17