I am currently trying to access my database but receive the message
Undefined variable: link
My code is as follows:
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'penbird098');
define('DB_NAME', 'cmstest');
$link = @mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(mysqli_error($link));
mysqli_set_charset($link, 'utf8');
function getPosts(){
$query = "SELECT * FROM post" or die($link);
$result = mysqli_query($link, $query);
$num = mysqli_num_rows($result);
if($num > 0){
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo $row['Title'];
}
}
}
getPosts();
What am I doing wrong? I have read the code and re-read it several times as well as looking around on Google and randomly trying different possibilities, but cant work out why. I’m guessing its something to do with not being able to pass a variable from outside a function into a function, but if I’m right, I don’t know how to do this or what the best way would be to do it, advice will be gratefully received.
Also I’m trying to use best practice with my code, so anything else which isn’t right would be good to know.
PS
the connection is in includes/connect
the function is in includes/functions
Calling the function is in index
Add the following line to your function:
See this reference on using global variables in a function scope: http://php.net/manual/en/language.variables.scope.php
From the above reference: