Function Doesn't Recognize Link To Database?

Hey there,

I am having some difficulties with a website I am attempting to create.

My problem is that in a particular file (called meta.php), I create a query to access information from my database… But, for whatever reason, it gives an error saying that it doesn’t know what $link is.

Now, $link is my string for connecting to the database.

Here is my first file that calls the database.php and meta.php files:

<?php

require "./includes/database.php";
require "./includes/meta.php";

$meta = new meta();

?>

Here is the meta.php file:

<?php

class meta {

function blog_author() {

$author_a = $link->query("SELECT author FROM pb_website");
$author_b = $author_a->fetch_object();

return $author_b->author;

}

}

?>

And finally, here is the file for my database:

<?php

@$link = new mysqli("localhost", "root", "password", "testing");

if ($link->connect_error) {

die ("Unable to connect to database: " . $link->connect_error);

}

?>

Please note that I call the blog_author() function in the first file by using echo $meta->blog_author();.

As I said earlier, meta.php doesn’t seem to know what $link is, even though I executed its value by requiring it in the first file.

What am I doing wrong?

$link is not getting passed into the class, so as far as the class is concerned, $link has not been set.

You would have to do something like this:



$meta = new meta( $link );

meta file:

class meta {
public $link;

function __construct( $link ) {

$this->link = $link;

}

function blog_author() {

$author_a = $this->link->query("SELECT author FROM pb_website");

$author_b = $author_a->fetch_object();

return $author_b->author;

}

}

Quick and dirty. You can certainly do this other ways. I realized that I don’t know what php version you are using, so exact coding specifics might have to be modified.

Unless something exists in the global scope, it has to specifically be passed to the function/class to be used.

Interesting.
This never happened in the past when I used MySQL… But I suppose MySQLi is treated differently. Well, the script works. Thank you. :smiley:

The procedural style creates the connection and then just uses the last open connection, which seems to be a hidden global. Mysqli object style uses the object to pass everything, and that object has to be explicitly passed to each function in order to work.

I’m glad it worked for you. Good luck on the rest.