简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM