我正在将部分代码从 mySQL 迁移到 PDO,但我似乎看不出我的代码有什么问题。
我有一个 try/catch 语句和错误报告,但我什么也没得到。
这里有人能看出哪里出了问题吗?
与此问题相关的文件是:
db_pdo.php
<?php
// Define connection
$db_host = "localhost";
$db_name = "winestore";
$db_user = "user";
$db_pass = "pass";
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
search.php
<?php
require_once ("MiniTemplator.class.php");
function getSearch($tableName, $attributeName) {
try {
require ("db_pdo.php");
$query = "SELECT DISTINCT {$attributeName} FROM {$tableName} ORDER BY {$attributeName}";
return $db->query($query);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
}
function generatePage(){
$t = new MiniTemplator;
$t->readTemplateFromFile ("search_template.htm");
$rows = getSearch("region", "region_name");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('regionName', $row['region_name']);
$t->addBlock("regionName");
}
$rows = getSearch("grape_variety", "variety");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('variety', $row['variety']);
$t->addBlock("variety");
}
$rows = getSearch("wine", "year");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('minYear', $row['year']);
$t->addBlock("minYear");
}
$rows = getSearch("wine", "year");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$t->setVariable('maxYear', $row['year']);
$t->addBlock("maxYear");
}
$t->generateOutput();
}
generatePage();
?>
最佳答案
您正在存储在 $rows
中,但之后使用 $result
,该结果将为空。
// $rows = getSearch("region", "region_name");
// should be this:
$result = getSearch("region", "region_name");
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
旁注:每次搜索都会创建一个新的数据库连接。您应该存储您的 $db
对象并重用它,而不是创建它的新实例。我建议将所有这些函数包装在存储它的类中,但由于您声明要迁移现有代码,您可以使用 global $db
将现有对象拉入变量范围你的功能:
// include this file once at the beginning of your script
require_once("db_pdo.php");
function getSearch($tableName, $attributeName) {
global $db; // pull $db inside the variable scope
try {
// ...
关于PHP 和 PDO - 从 MySQL 迁移 - 不显示结果或错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25622658/