The cart is empty

Developing applications in PHP often involves working with databases, where one common task is securing the application against SQL injections. The function mysql_real_escape_string() used to be a standard tool for this purpose in PHP. This function is designed to escape special characters in strings used in SQL queries, thereby helping to prevent potential attacks. However, encountering the "Fatal error: Call to undefined function mysql_real_escape_string()" indicates that your application attempts to call a function that is no longer defined in the current version of PHP.

Causes of the Error

The error "Fatal error: Call to undefined function mysql_real_escape_string()" typically appears for one of these reasons:

  1. Outdated Code: The mysql_real_escape_string() function belongs to the MySQL extension, which was deprecated in PHP version 5.5.0 and removed altogether in PHP 7.0.0. If your code still uses this function, it will be incompatible with newer PHP versions.

  2. Disabled MySQL Extension: The old MySQL extension providing the mysql_real_escape_string() function might not be enabled on the server, causing calls to this function to fail.

How to Fix the Error

Updating Your Code: The best solution is to update your code to be compatible with the newer MySQLi extension or with PDO (PHP Data Objects). These are modern and secure alternatives to the removed MySQL extension.

Switching to MySQLi:

  • The mysql_real_escape_string() function has an equivalent in MySQLi, mysqli_real_escape_string().
  • This function requires that the first parameter be a link identifier to the database connection:
    $conn = mysqli_connect("hostname", "username", "password", "database");
    $safe_string = mysqli_real_escape_string($conn, $unsafe_string);
    ​

Using PDO:

  • PDO offers an even better way to work with databases through prepared statements, which automatically handle all input strings and simplify working with different database systems.
  • An example of a prepared statement with PDO:
    $pdo = new PDO("mysql:host=hostname;dbname=database", "username", "password");
    $stmt = $pdo->prepare("INSERT INTO table (column) VALUES (:value)");
    $stmt->bindParam(':value', $unsafe_string, PDO::PARAM_STR);
    $stmt->execute();
    ​

 

Fixing the "Fatal error: Call to undefined function mysql_real_escape_string()" requires updating outdated code. By transitioning to the MySQLi extension or using PDO, not only will you solve this problem, but you will also increase the security and flexibility of your application. Regularly reviewing and updating source code to conform with the latest standards and recommendations is key to safe and efficient application development.