creptor4
creptor4

Reputation: 121

What's the best way to retrieve data from a database and pass it as variables

So I have done some searching but the results seems to be kind of scrambled, that's why I'm asking here.

The problem is that I have a setup.php file, in which I preload the options that are needed to load some things in the page, and I don't know if this is the best method.

Here is the code:

function fetch_site_option($id){
    $conn=Core::getInstance()->db->prepare("SELECT value FROM options WHERE id = ?");
    $conn->bindParam(1,$id,PDO::PARAM_INT);
    $conn->execute();
    if($conn->rowCount()==1){
        $data=$conn->fetch(PDO::FETCH_ASSOC);
    }else{
        $data=null;
    }
    return $data['value'];
}

and the values that need to be retrieved:

$siteTitle=fetch_site_option('1');
$mainPage=fetch_site_option('2');
$debug=fetch_site_option('3');
$logo=fetch_site_option('4');
$sTT=fetch_site_option('5');

This repeats a lot of times, and that's why it needs to be very efficient.

Thanks in advance.

Upvotes: 1

Views: 34

Answers (1)

Roman
Roman

Reputation: 2549

To be more efficient, you should try to merge your multiple requests into one. Try something like this:

SELECT id, value FROM options WHERE id IN (?,?,?,?,?)

This will return all required rows in one request. Instead of returning one value at a time, you should change the function fetch_site_option() to return an array of ids and values.

Upvotes: 1

Related Questions