使用PHP连接到MySQL数据库,错误'不在对象上下文中时使用$ this'

I don't know how to write PHP functions.
I'm getting this error 'Using $this when not in object context'.
I've only inserted the lines 3 and 4 (the MySQL connection code), the rest of the code is fine.
How do I fix these lines?

<?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);
?>
  1. $this is only used within a class when you want to refer to a property or function of the class you are working inside of.
  2. You're not in a class, so replace $this->connection with $connection.
  3. Avoid using mysql_* functions, they are deprecated. You'll be doing yourself a favor by learning either PDO or mySQLi instead.

You can't use $this outside of an object class, which is what appears to be happening here. Just rename $this->connection to $connection in all locations.

Note that you also should not be using mysql_* functions at all, as these are deprecated. You might want to use mysqli_* functions instead.

Just remove the keyword "this" and the pointer "->"

<?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 has value only inside a defined class. i.e, we generally use it while defining a class to point to a method or property in that class.

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

This'll work just fine.

By the way use mysqli_* or pdo for better results.