PHP分页功能异常排查请求:初始正常点击页码报错
Hey Colin, let's work through this pagination issue together—it's a common snag when building this feature, so we'll get it sorted out quickly!
The Core Issue
When you load index.php without a page parameter, everything works, but clicking pagination links like index.php?page=1 throws an error saying $query is 0. That means your database query is failing specifically when the page parameter is present. Here are the most likely fixes:
1. Fix Invalid page Parameter Handling
The first thing to check is how you're processing the page GET parameter. If you're using it directly without validation, it could be causing invalid SQL syntax. For example:
- If
pageis a non-numeric value (like a string), it breaks theLIMITclause. - If
pageis 0 or negative, the offset calculation becomes invalid.
Fix it with safe parameter handling:
// Define how many items per page $items_per_page = 10; // Sanitize and validate the page number $current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1; // Ensure we never go below page 1 $current_page = max($current_page, 1); // Calculate the offset for the SQL query $offset = ($current_page - 1) * $items_per_page;
2. Debug the SQL Query
When $query returns 0 (false for older MySQL extensions), you need to see exactly what's wrong with your SQL. Add error checking right after your query:
// Example query (adjust table/columns to match your setup) $query = "SELECT * FROM your_table LIMIT $offset, $items_per_page"; $result = mysql_query($query); // Check for query errors if (!$result) { die('Database Error: ' . mysql_error()); }
This will print the exact MySQL error message (like a syntax mistake or invalid offset) which tells you exactly what's broken.
3. Verify Offset Calculation
If your offset is negative (e.g., if page was 0 before validation), MySQL will reject the query. The code in step 1 fixes this by forcing current_page to be at least 1, but double-check your offset math:
// Correct offset formula: (page number - 1) * items per page $offset = ($current_page - 1) * $items_per_page;
4. Bonus: Use Modern Database Extensions
The old mysql_* functions are deprecated—switch to MySQLi or PDO for better security and error handling. Here's a quick MySQLi example with prepared statements (prevents SQL injection even if parameters aren't sanitized):
$conn = mysqli_connect('localhost', 'username', 'password', 'dbname'); $stmt = $conn->prepare("SELECT * FROM your_table LIMIT ?, ?"); $stmt->bind_param("ii", $offset, $items_per_page); $stmt->execute(); $result = $stmt->get_result();
Quick Test
After applying the parameter validation, load index.php?page=2 again. If the error persists, the debug code from step 2 will show you exactly what's wrong with the SQL—this is the fastest way to pinpoint the issue.
内容的提问来源于stack exchange,提问作者Colin Burt

