I'm trying to load some data from a database using PHP, but for some reason it doesn't work when I put it inside a function. If I try the code without a function, it works fine:
//$dbc connection
$call1 = 0;
$output = '';
$query = "select * from artists order by lname limit $call1, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
However, when I change the code to be inside a function, I don't get anything from the database (or at least it won't return anything):
//$dbc connection
$call1 = 0;
$output = '';
function loadArtists($call){
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
}
loadArtists($call1);
What am I doing wrong here?
You cannot use $dbc in your function, because it is a global variable.
You can use either
function loadArtists($call){
global $dbc;
...
}
to make $dbc known to loadArtists() or pass it as a second parameter
function loadArtists($dbc, $call){
...
}
and call it as
loadArtists($dbc, $call1);
As I mentioned in one of my comments, using global to fix the scope of your connection is poor practice. The correct way to pass your connection is like so:
$dbc = mysqli_connect("localhost", "my_user", "my_password", "world");
$call1 = 0;
$output = '';
function loadArtists($call, $dbc){
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
}
loadArtists($call1, $dbc);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With