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);
?>
$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.$this->connection
with $connection
.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.