PHP文章发布系统详情页报article_id数组键未定义错误如何解决
错误原因
Article类的fetch_data方法返回格式错误:查询单条文章时使用了fetchAll(),该方法会返回二维数组(外层是查询结果集数组,内层才是单条文章的字段数组),直接访问$data['article_id']不存在,正确应该用fetch()返回单条一维数组。artikkeli-sivu.php没有做参数合法性校验和变量初始化:如果用户直接访问该页面不传id参数,或者传入的id在数据库中不存在,$data变量不会被定义,访问时必然报错。- 小问题:
connection.php中连接成功后输出<h3>Yhteys luotu!</h3>会破坏所有引入该文件页面的HTML结构,需要删除。
修复步骤
1. 修复article.php的fetch_data方法
<?php class Article { public function fetchAll(){ global $pdo; $query = $pdo->prepare("SELECT * FROM artikkelit"); $query->execute(); return $query->fetchAll(); } public function fetch_data($article_id){ global $pdo; $query = $pdo->prepare("SELECT * FROM artikkelit WHERE article_id= ?"); $query->bindValue(1, $article_id); $query->execute(); // 单条查询用fetch()返回一维数组 return $query->fetch(); } } ?>
2. 修复artikkeli-sivu.php的参数校验和变量初始化
<!DOCTYPE html> <?php include_once 'connection.php'; include_once 'article.php'; $article = new Article; // 先初始化$data为false,避免未定义报错 $data = false; if(isset($_GET['id']) && is_numeric($_GET['id'])) { $id = (int)$_GET['id']; $data = $article->fetch_data($id); } ?> <html> <head> <meta charset="UTF-8"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet"> <style> body, html { margin: 0; padding: 0; text-align: center; } .back-button { position: relative; top: 500px; width: 140px; height: 45px; border-radius: 25px; font-size: 18px; font-family: 'Roboto', arial; font-weight: 500; letter-spacing: 2px; background-color: white; box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.1); border: none; transition: 0.3s ease 0s; cursor: pointer; outline: none; } .back-button:hover { background-color: #24a0ed; box-shadow: 0px 5px 20px #6bbff2; color: #fff; transform: translateY(-3px); } .article-container { background-color: white; width: 500px; height: 400px; margin: 0 auto; box-shadow: 0px 0px 1px 1px lightgrey; } h1 { text-align: center; font-family: 'Roboto', sans-serif; font-weight: 500; } </style> </head> <body> <h1> Artikkelit </h1> <div class="article-container"> <?php // 先判断文章是否存在再输出内容 if($data){ echo $data['article_id']; // 后续输出文章标题、内容等字段也在此处添加即可 }else{ echo "文章不存在或参数错误"; } ?> </div> <a class="back-link" href="index.php"><button class="back-button">Back</button></a> </body> </html>
3. 修复connection.php的多余输出
<?php $servername = "localhost"; $username = "root"; $password = ""; $database = "cms"; try { $pdo = new PDO('mysql:host=localhost;dbname=cms', 'root', ''); // 删除连接成功的多余输出,避免破坏页面结构 // echo "<h3>Yhteys luotu!</h3>"; } catch(PDOException $e) { exit('Epäonnistui'); } ?>
内容的提问来源于stack exchange,提问作者Kasper Kuula
相关产品推荐
相关产品推荐

