Unable to call function

Hello. I am trying to establish a new connection to my local database. Also using this connection I am trying to create a query to retrive data, but for some reason calling getData function does not return any results. I guess I am not establishing the connection right or there is something else, because when I try to just have the code with no class and functions it works. Any suggestions

Thanks

 <?php

 class Database{



 public $link;

public function connect(){
$link = new mysqli("localhost","root","root","Users");
if (mysqli_connect_error())
{
	echo mysqli_connect_error();
	exit();
}
else
	$this->$link;


    }

     public function getData(){
	$query = "SELECT * FROM users";
	if ($result = mysqli_query($link, $query)) 
	{
	    while ($row = mysqli_fetch_assoc($result)) 
	    {
	        	$row = array_map('stripslashes', $row);
				$push[] = $row;
	    }

	   
	}
	return $push;
}

   }

   ?>

This is the file from where I am trying to call the function.

  <?php


    $me = new Database(); 
   $me->connect();
   $array = $me->getData();

echo "<table border= 1px><br>"; // start a table tag in the HTML
echo "<tr>
		<th>ID</th>
		<th>Password</th>
		<th>First Name</th>  
		<th>Last Name</th>
	   </tr>";

foreach ($array as $row) 
{
echo 
"<tr>
	<td>" . $row['user_id'] . "</td>
	<td>" . $row['user_password'] . "</td>
	<td>" . $row['user_first_name'] .  "</td>
	<td>" . $row['user_last_name'] .  "</td>
</tr>";  //$row['index'] the index here is a field name
}	
echo "</table>";

   ?>
public function getData(){
	$query = "SELECT * FROM users";
    if ($result = mysqli_query($link, $query))
    ...

That looks like it should be

if ($result = mysqli_query($this->link, $query)

Otherwise, the $link variable is undefined when you get to that line…

And the $link variable itself doesn’t look to get properly assigned in the connect method - that should probably look like

$this->link = $link;

HTH!

1 Like

Yes, it works. I thought that to proper refer to the link I should have used $ in front. Apparently not.
Thanks for the help

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.