我无法使用'fetch(PDO :: FETCH_ASSOC)'从表中获取数据

时间:2014-08-29 00:19:31

标签: php sql select pdo

为什么fetch (PDO::FETCH_ASSOC)无法正常工作?如何在没有foreach循环的情况下从表中获取我想要的数据?我之前使用$statement变量来准备/执行另一个查询。这可能是问题吗?

try
{
    $database = new PDO ('mysql:host=localhost;dbname=youdonotneedtoknow;charset=utf8', 'youdonotneedtoknow', 'youdonotneedtoknow');
    $database -> setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $database -> setAttribute (PDO::ATTR_EMULATE_PREPARES, true);

    //Read
    $statement = $database -> prepare ('SELECT * FROM edit');
    $statement -> execute ();
    while ($row = $statement -> fetch (PDO::FETCH_ASSOC))
    {
        $windowTitle = $row ['windowTitle'];
        $bodyBackgroundColour = $row ['bodyBackgroundColour'];
        $divisionBackgroundColour = $row ['divisionBackgroundColour'];
    }
}
catch (PDOException $exception)
{
    die ('Error: ' . $exception -> getMessage () . '<br><br>' . 'Por favor diríjase a "index.php" en este mismo directorio y contacte a su administrador.');
}

1 个答案:

答案 0 :(得分:2)

这样做:

while ($row = $statement -> fetch (PDO::FETCH_ASSOC))
{
    switch ($row['id']) {
        case 'windowTitle':
            $windowTitle = $row ['value'];
            break;
        case 'bodyBackgroundColour':
            $bodyBackgroundColour = $row['value'];
            break;
        case 'divisionBackgroundColour':
            $divisionBackgroundColour = $row['value'];
            break;
    }
}

您也可以使用变量:

while ($row = $statement -> fetch (PDO::FETCH_ASSOC))
{
    ${$row['id']} = $row['value'];
}