MySQLi预处理语句迁移疑问:代码执行后输出异常求助
Fixing Your MySQLi Prepared Statement Issues
Hey there! Let's walk through the problems in your current code and get your prepared statement working as expected.
First, let's spot the key issues:
- You don't need
real_escape_stringwith prepared statements: The parameter binding system handles escaping automatically, so manually escaping$post_idis redundant and might even corrupt your data (e.g., if the ID has legitimate characters that get escaped unnecessarily). bind_result()is missing parameters: This method needs you to pass variables that will hold the values from each column you're selecting. Without specifying these, you can't retrieve any data from the query.- You're not fetching the results: After executing the statement, you need to either store the result set or fetch the rows to access the data.
Here's a corrected version using bind_result():
// Get the ID from the request (no need for real_escape_string!) $post_id = $_GET['id']; // Prepare the query (specify columns instead of * for clarity) $query_blog = 'SELECT id, title, content FROM blog WHERE id = ?'; $result_blog = $mysqli->prepare($query_blog); // Bind the integer parameter (i = integer type) $result_blog->bind_param('i', $post_id); // Execute the statement $result_blog->execute(); // Bind result columns to variables (match the order in your SELECT clause) $result_blog->bind_result($id, $title, $content); // Fetch the row to populate the bound variables $result_blog->fetch(); // Now you can verify the data echo "Post ID: $post_id<br>"; echo "Query: $query_blog<br>"; echo "Fetched Post Title: $title"; // Clean up resources $result_blog->close(); $mysqli->close();
A more concise alternative using get_result() (if your setup supports it):
This method lets you use familiar fetch_assoc() like you would with a regular query result, which is often easier to work with:
$post_id = $_GET['id']; $query_blog = 'SELECT * FROM blog WHERE id = ?'; $result_blog = $mysqli->prepare($query_blog); $result_blog->bind_param('i', $post_id); $result_blog->execute(); // Get the result set as a mysqli_result object $blog_result = $result_blog->get_result(); // Fetch the row as an associative array $blog_post = $blog_result->fetch_assoc(); // Verify the data echo "Post ID: $post_id<br>"; echo "Query: $query_blog<br>"; print_r($blog_post); // Shows all columns from the matched row // Clean up $result_blog->close(); $mysqli->close();
Why your original output seemed off:
When you printed $post_id, using real_escape_string might have modified the value (though less likely for integers). The bigger issue was that you weren't actually fetching any results from the query, so you couldn't confirm if the statement was retrieving the correct data.
内容的提问来源于stack exchange,提问作者Beji
相关产品推荐
相关产品推荐

