簡體   English   中英

使用PHP連接到MySQL數據庫,錯誤“不在對象上下文中時使用$ this”

[英]Connect to MySQL DB using PHP, error 'Using $this when not in object context'

我不知道如何編寫PHP函數。
我收到此錯誤“不在對象上下文中時使用$ this”。
我只插入了第3行和第4行(MySQL連接代碼),其余的代碼都沒問題。
如何解決這些問題?

<?php

 $this->connection = mysql_connect('localhost', 'mbrconsu_un394x', 'y1cz9,rd+hf6') or die(mysql_error());
 mysql_select_db('mbrconsu_mmx', $this->connection) or die(mysql_error());

$sql="SELECT tema FROM treinamentos ORDER BY tema ASC";
$result = mysql_query($sql);
$stack=array();
    while($row = mysql_fetch_array($result))
          {
            array_push($stack,array($row['column1'],$row['column2']));
          }

echo json_encode($stack);
?>

您不能在對象類之外使用$this ,這似乎在這里發生。 只需重命名$this->connection$connection的所有位置。

注意,也不建議使用mysql_*函數,因為這些函數已被棄用。 您可能要改用mysqli_*函數。

  1. $this僅在您要引用要在其中使用的類的屬性或函數時在類中使用。
  2. 您不在課程中,因此將$this->connection替換$this->connection $connection
  3. 避免使用mysql_ *函數,因為它們已被棄用。 通過學習PDO或mySQLi可以幫自己一個忙。

只需刪除關鍵字“ this”和指針“->”

<?php 

$connection = mysql_connect('localhost', 'mbrconsu_un394x', 'y1cz9,rd+hf6') or die(mysql_error());
mysql_select_db('mbrconsu_mmx', $connection) or die(mysql_error());

$sql="SELECT tema FROM treinamentos ORDER BY tema ASC";
$result = mysql_query($sql);
$stack=array();
    while($row = mysql_fetch_array($result))
          {
            array_push($stack,array($row['column1'],$row['column2']));
          }

echo json_encode($stack);

?>

$this僅在定義的類內具有值。 即,我們通常在定義類時使用它來指向該類中的方法或屬性。

mysql_connect('localhost', 'mbrconsu_un394x', 'y1cz9,rd+hf6') or die(mysql_error());
mysql_select_db('mbrconsu_mmx') or die(mysql_error());;

這樣就可以了。

順便說一句,使用mysqli_*pdo可獲得更好的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM