douwen6274 2014-10-08 12:22
浏览 13
已采纳

获取整个表并将其放入变量中

I'd need to put all the values from table Status in to variables. I'd guess this would not be the best way of doing it how I've done it below. I've tried using PDO::FETCH_ASSOC which I can't get to work. How should I do this correctly? Thanks.

My table named Status:

------------------
|  Rule  | Value |
|----------------|
| Active |   1   |
|Version |  102  |
| Limit  | 15000 |
------------------

My code:

function checkStatus($connection, $rule) {
$query = $connection->prepare('SELECT Value FROM Status WHERE Rule=?');
$query->execute(array($rule));
$result = $query->fetchColumn();
return (int)$result;
}

try {
$connection = new PDO("mysql:host=localhost;dbname='something';charset=utf8", 'username', 'password');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $ex) { //do-stuff }

$active = checkStatus($connection, "Active")
$version = checkStatus($connection, "Version")
$limit = checkStatus($connection, "Limit")

This works the way I want it to work, but how can I do this with just one query to the db and then put the results in the variables since I have around 10 of them at the moment?

  • 写回答

1条回答 默认 最新

  • dousuowu4610 2014-10-08 12:26
    关注
    $query = $connection->prepare('SELECT Value, Rule FROM Status');
    $query->execute(array($rule));
    $result = $query->fetchAll();
    foreach ($result as $val)
    {
        ${strtolower($val['Rule'])} = $val['Value'];
    }
    
    echo "$active, $version, $limit"; //1, 102, 15000
    

    This will do the same thing (place them in the same variable). This is called super variables (create a variable which name is based on a string).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?