OOP PHP项目中使用mysqli_real_escape_string转义字符串的写法是否正确?
Hey there! Let's take a look at your escape function and break down its validity, along with better practices for modern PHP development.
First off, your code is syntactically correct—it will run without errors assuming $this->connection is a valid mysqli connection object. But there are key caveats and more reliable approaches to consider:
Issues with your current implementation
- Character set dependency:
mysqli_real_escape_stringrelies entirely on the character set configured for your database connection. If you haven't explicitly set it to a modern standard likeutf8mb4(to support full Unicode), this function won't properly escape all characters, leaving you vulnerable to SQL injection in edge cases. - Procedural style in an OOP class: You're using the procedural
mysqli_real_escape_string()function, but since you're working within an OOP class that holds a connection object, using the OOP method version is more consistent with your code structure. - Manual escaping is outdated: Manual string escaping is no longer the recommended approach for preventing SQL injection. Prepared statements are far more reliable and eliminate the need for manual escaping entirely.
Improved escape function (if you still need to use escaping)
If you have a specific use case where escaping is necessary instead of prepared statements, here's a more robust OOP-style implementation:
public function escape($string) { // Explicitly set the connection charset to ensure proper escaping $this->connection->set_charset('utf8mb4'); // Use the OOP method of the mysqli connection object return $this->connection->real_escape_string($string); }
Recommended: Use Prepared Statements Instead
The best practice for secure database interactions in PHP is to use prepared statements. They separate SQL logic from user input at the database level, making SQL injection impossible by design. Here's an example implementation for your OOP class:
public function getUserNameById($userId) { // Prepare the SQL statement with a placeholder for input $stmt = $this->connection->prepare("SELECT username FROM users WHERE id = ?"); // Bind the input parameter: "i" indicates an integer type // Use "s" for strings, "d" for decimals, "b" for blobs $stmt->bind_param("i", $userId); // Execute the prepared statement $stmt->execute(); // Bind the result to a variable $stmt->bind_result($username); // Fetch the result $stmt->fetch(); // Clean up resources $stmt->close(); return $username; }
Prepared statements remove the guesswork from input handling and are the industry standard for secure database operations.
内容的提问来源于stack exchange,提问作者Iam Loki

