我在连接中将PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
设置为默认值,现在我遇到了fetchAll问题。
我遇到的问题是:
Notice: Undefined offset: 0 in C:\wamp\www\a\test.php on line 59
第59行是:
if($sql->fetchAll()[0][0] !== '0' && $level !== 0){
这是我的连接类型:
$host = 'localhost';
$db = 'demo';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => TRUE,
);
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
这是我正在尝试的查询:
如果我删除ATTR_DEFAULT_FETCH_MODE
可以正常工作,是否可以同时使用两者?
function bootstrap_menu($pdo, $parent_id, $level = null) {
$stmt = $pdo->prepare("SELECT * FROM categories WHERE parent_id =:parent_id");
$stmt->bindParam(":parent_id", $parent_id, PDO::PARAM_INT);
$stmt->execute();
foreach ($stmt->fetchAll() as $row) {
$sql = $pdo->prepare("SELECT count(*) FROM categories WHERE parent_id =:cat_id");
$sql->bindParam(":cat_id", $row['cat_id'], PDO::PARAM_INT);
$sql->execute();
if($sql->fetchColumn()[0][0] !== '0' && $level !== 0){
echo "<li class=\"nav-item dropdown\">\n";
echo "<a class=\"nav-link dropdown-toggle\" href=\"".htmlspecialchars($row['seo_url'])."\" id=\"navbarDropdown\" role=\"button\" data-toggle=\"dropdown\"
aria-haspopup=\"true\" aria-expanded=\"false\">\n";
echo $row['cat_name'];
echo "</a>\n";
echo "<ul class=\"dropdown-menu\" aria-labelledby=\"navbarDropdown\">\n";
bootstrap_menu($pdo, $row[0], $level - 1);
echo "</ul>\n";
echo "</li>\n";
}elseif($level == 0){
$my_class = htmlspecialchars($row['cat_name']);
if($my_class == 'Ana Sayfa'){
echo "<li class=\"nav-item active\">\n";
echo "<a href=\"".htmlspecialchars($row['seo_url'])."\" class=\"nav-link \">\n";
echo htmlspecialchars($row['cat_name']);
echo "</a>\n";
echo "</li>\n";
}else{
echo "<li class=\"nav-item\">\n";
echo "<a href=\"".htmlspecialchars($row['seo_url'])."\" class=\"nav-link\">\n";
echo htmlspecialchars($row['cat_name']);
echo "</a>\n";
echo "</li>\n";
}
}
else {
echo "<li class=\"dropdown-item\">";
echo "<a href=\"".htmlspecialchars($row['seo_url'])."\" class=\"dropdown-item\">\n";
echo htmlspecialchars($row['cat_name']);
echo "</a>\n";
echo "</li>\n";
}
unset($sql);
}
unset($stmt);
}
答案 0 :(得分:1)
$sql->fetchAll()[0][0]
仅表示第一行的第一列。 PDO fetchColumn()
中已经有一种解决方法。
您只需要:
if($sql->fetchColumn() !== '0' && $level !== 0)
甚至更好
if($sql->fetchColumn() && $level !== 0)
如果出于任何原因仍要使用fetchAll()
,则可以将访存样式作为参数传递。例如$sql->fetchAll(\PDO::FETCH_BOTH)
也实际上不需要外部循环foreach ($stmt->fetchAll() as $row)
。只需foreach ($stmt as $row)