0
我已經在本地主機上測試嫩枝...這裏的代碼是一樣this question但查詢是不同的:枝條和錯誤消息 - 這是正常的嗎?
<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
$dbh = new PDO('mysql:dbname=world;host=localhost', 'root', 'mypass');
} catch (PDOException $e) {
echo "Error: Could not connect. " . $e->getMessage();
}
// set error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// attempt some queries
try {
// execute SELECT query
// store each row as an object
$sql = "SELECT manufacturer, model, modelinfo FROM automobiles WHERE id = '4' ";
$sth = $dbh->query($sql);
while ($row = $sth->fetchObject()) {
$data[] = $row;
}
// close connection, clean up
unset($dbh);
// define template directory location
$loader = new Twig_Loader_Filesystem('templates');
// initialize Twig environment
$twig = new Twig_Environment($loader);
// load template
$template = $twig->loadTemplate('cars.html');
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>
我有3條記錄;我決定查詢一個不存在的記錄,看看Twig的錯誤處理是什麼樣的,因爲我正在比較Twig和Smarty - 出於興趣和項目。 此錯誤消息出現:
Notice: Undefined variable: data in /Applications/MAMP/htdocs/mysite/twigtesting.php on line 42
無疑公告稱「數據沒有發現」應該發生或我錯了嗎? 未定義的變量數據是指:
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
這究竟是爲什麼?我是Twig的新手,並使用他們網站的最新版本,這是相關的。