Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying a database within a PHP function [duplicate]

Tags:

php

mysql

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?

like image 995
misdreavus79 Avatar asked Nov 20 '25 17:11

misdreavus79


2 Answers

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);
like image 150
Olaf Dietsche Avatar answered Nov 23 '25 10:11

Olaf Dietsche


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);
like image 43
Kermit Avatar answered Nov 23 '25 09:11

Kermit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!