php 注意:第 63 行未定义变量:mysqli in...

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10482574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:17:26  来源:igfitidea点击:

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

phpajaxmysqli

提问by Niels

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.

我收到此错误,我真的不知道该怎么办。我正在努力构建一个“表单”,您可以使用它向数据库中添加信息。因为我不想在我的数据库中出现双重记录,所以我正在使用 AJAX 检查一些字段。

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

在这里您可以看到我的类的代码,我从中收到了错误。(我使用 mysqli - 语言)

<?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

有没有人有办法解决吗?或者你也想看看我的 ajax 文件和 .php 页面吗?谢谢

EDIT

编辑

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

这是我的 add.php 文件(至少所有重要的东西)

<?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

这是我的ajax文件

<?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

好的,我尝试了您的几种解决方案,但没有一个有效。我可能是我的错,但我想出了一些办法,我用 INCLUDE 替换了 INCLUDE_ONCE,现在我可以在没有 AJAX 的情况下向我的数据库添加一些东西,但是当我使用 AJAX 时,表单会检查这些值是否已经在数据库中,但是当我添加它们,没有任何反应。我也没有收到任何错误。我也从 ajax 收到了正确的信息。有人可以帮忙吗?谢谢你

回答by John Conde

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:

您不应该在方法声明中使用包含。这是一个不好的做法。首先在构造函数中将 MySQLi 对象作为参数传递:

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

回答by raina77ow

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 singletonclass, with both constructor and __clone method made private. Like this:

文件本身通常是一个单例类,构造函数和 __clone 方法都是私有的。像这样:

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.

...包括该类文件仅一次。

回答by Andreas Stokholm

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

一个快速而肮脏的解决方案是使用数据库访问在您的方法中添加全局 $mysqli。像这样

    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 reallydirty! - But the way you've made it will require a pretty huge restructuring if it is to be made otherwise.

脏,我的意思是真的很脏!- 但是如果要以其他方式制作它,您制作它的方式将需要进行相当大的重组。

回答by synkro

There was a small mistake in raina′s answer, which prevented the proper script execution:

Raina 的回答有一个小错误,导致脚本无法正确执行:

if (!isset(self::$connection)

should be

应该

if (!isset(self::$connection))