为什么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.');
}
答案 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'];
}