PHP通过$_GET验证文章存在时参数错误无输出的问题求助
问题分析与解决思路
Hey there, let's fix that missing "No content" message issue! The root problem here is how you're checking for results: when your query doesn't find any matching articles, the fetch() method returns false immediately, so your while loop never runs at all. That's why you see nothing when the numArticle parameter is wrong.
Here's how to fix this step by step:
- Check for results outside the loop:Instead of trying to validate inside the
whileblock, first run your query, then userowCount()to check if any rows were returned. If the count is 0, output your "No content" message right away. - Validate the input first:Before even running the query, make sure
$_GET['numArticle']is a valid integer (since article IDs are usually numeric). This helps prevent SQL injection and avoids errors from non-numeric values. - Handle missing parameters:Add a check for when
numArticleisn't present in the$_GETarray at all, to avoid PHP notices.
Improved Code Example
// First, handle missing or invalid numArticle parameter if (!isset($_GET['numArticle']) || !filter_var($_GET['numArticle'], FILTER_VALIDATE_INT)) { echo 'Invalid or missing article ID'; exit; } $articleId = $_GET['numArticle']; // Prepare and execute the query $stmt = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?'); $stmt->execute([$articleId]); // Check if any rows were returned if ($stmt->rowCount() === 0) { echo 'No content'; } else { // If you need to process the content, you can fetch it here $data = $stmt->fetch(); echo 'Can load the page'; // Optional: Use $data['content'] to display the article content } $stmt->closeCursor();
Key Notes:
- Using
rowCount()gives you a direct count of matched rows, so you don't have to rely on thefetch()return value to detect missing results. - The input validation step ensures you're only passing valid integers to your query, which is a critical security practice.
- Adding a check for
isset($_GET['numArticle'])prevents PHP from throwing an "Undefined index" notice when the parameter is missing.
内容的提问来源于stack exchange,提问作者JFM
相关产品推荐
相关产品推荐

